Home > Web Front-end > JS Tutorial > body text

Let's talk about Ajax in jQuery and explain its main methods in detail

青灯夜游
Release: 2022-03-15 11:12:13
forward
3196 people have browsed it

This article will take you to understand Ajax in jQuery, talk about the advantages and disadvantages of Ajax, and have an in-depth understanding of the main methods of Ajax. I hope it will be helpful to everyone!

Let's talk about Ajax in jQuery and explain its main methods in detail

Preface

This article refers to and quotes "Sharp JQuery" to provide a detailed explanation of jQuery-Ajax and its main methods.

1. Advantages and Disadvantages of Ajax

1. Advantages of Ajax

a. No browser plug-ins are required
No need for any Browser plug-ins are supported by most browsers, and users only need to allow JavaScript to execute on the browser.

b. Excellent user experience.
The biggest advantage is that the data can be updated without refreshing the entire page, which allows the web application to respond quickly to user operations.

c. Improve the performance of Web programs
Compared with the traditional mode, the biggest difference in performance of the Ajax mode is the way of transmitting data. In the traditional mode, data submission is It is implemented through the form (from), and the data is obtained by fully refreshing the web page to obtain the content of the entire page. The Ajax mode only submits the data that needs to be submitted to the server through the XMLHttpRequest object, that is, it is sent on demand.

d. Reduce the burden on the server and broadband
The working principle of Ajax is equivalent to adding an intermediate layer between the user and the server, which asynchronously asynchronousizes user operations and server responses. , he creates an Ajax engine on the client side, transferring some of the traditional server burden work to the client, making it easier for client resources to be processed, and reducing the burden on the server and broadband.

2. Shortcomings of Ajax

a. The browser’s insufficient support for the XMLHttpRequest object
One of the shortcomings of Ajax first comes from the browser, IE5. 0 and later versions only support the XMLHttpRequest object (most clients at this stage are above IE6). Mozilla, Netscape and other browsers support XMLHttpRequest even later. In order to enable Ajax applications to run normally in various browsers, the program Developers must spend a lot of effort coding to take into account the differences between browsers, so that Aajx applications can be better compatible with each browser.

b. Destroy the normal functions of the browser's forward and back buttons
In Ajax, the functions of the forward and back buttons will be invalid, although it can be done through certain methods (adding anchor points ) to enable users to use the forward and back buttons, but it is a lot more troublesome than the traditional method. For users, they often encounter this situation. When clicking a button to trigger an Ajax interaction, they feel that they do not want to do so. , and then habitually clicked the back button, and the most undesirable result occurred. The browser returned to the previous page, and the content obtained through Ajax interaction completely disappeared.

c. Insufficient support for search engines
Usually search engines use crawlers to search and organize billions of massive data on the Internet. However, crawler programs It is still not possible to understand those strange JavaScript codes and the resulting changes in page content, which puts Ajax-based sites at a disadvantage compared to traditional sites in network promotion.

d. Lack of development and debugging tools
JavaScript is an important part of Ajax. At present, due to the lack of good JavaScript development and debugging tools, many web developers Being intimidated by JavaScript makes writing Ajax code even more difficult. Warrior, many web developers are currently accustomed to using visual tools and are afraid of writing code themselves. This has affected everyone's application of Ajax to a certain extent.

2. Install the Web environment---AppServ

The Ajax method needs to interact with the Web server, so it requires an environment. AppServe is a toolkit for installing the environment.

Download address: https://www.appserv.org/en/download/

Installation: Single-machine Next button, enter common information such as website address, email address, password, etc., port The default is 80.

Enter "http://localhost:80" in the browser, and the following interface will appear, indicating that the installation is successful.

Lets talk about Ajax in jQuery and explain its main methods in detail

Usage: Copy the written program to the installed AppServ\www folder, and then enter "http://loaclhost:80/" in the address bar Program File Name" to access.

3. jQuery Ajax operation function

The jQuery library has a complete Ajax compatible suite. The functions and methods inside allow us to load data from the server without refreshing the browser.

https://www.w3school.com.cn/jquery/jquery_ref_ajax.asp

Lets talk about Ajax in jQuery and explain its main methods in detail

In the picture above, .Ajax()The method isjQu# The lowest method in ##ery, the layer 2 is .load(),.Ajax() method is the lowest method in jQuery, the second layer is .load(), layer is. load(), .get() and .po (

)

,

3

layer

is

.getScript() and $.getJSON() methods. Lets talk about Ajax in jQuery and explain its main methods in detail

1. $.ajax() method

I have previously published an article "Detailed explanation of jquery ajax-ajax() method"

For details, please click: https:/ /juejin.cn/post/7019188063704350756

2. The load() method

is the simplest and most commonly used method compared to other methods. It can load remote HTML code and insert it into the DOM.

Structure

load( url , [data] , [callback] )
Copy after login

Parameters

ApplicationLets talk about Ajax in jQuery and explain its main methods in detail

1) Load HTML document #########First build an HTML file (test.html) loaded by the load() method and appended to the page. The HTML code is as follows: ###
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>测试</title>
</head>
<body>
	<div>
		<p>hello world!</p>
		<ul>
			<li>C</li>
			<li>C#</li>
			<li>C++</li>
			<li>Java</li>
			<li>.Net</li>
			<li>JSP</li>
			<li>ASP</li>
			<li>PHP</li>
			<li>Python</li>
			<li>ios</li>
			<li>Android</li>
			<li>Javascript</li>
			<li>CSS</li>
			<li>HTML</li>
			<li>XML</li>
			<li>VUE</li>
			<li>React</li>
			<li>Angular</li>
			<li>SQL</li>
		</ul>
	</div>
</body>
</html>
Copy after login
###Then create a new blank page (main.html), including the button that triggers the Ajax event, and the ###### with the id "content" to display the appended HTML content (test.html ), the code is as follows:
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<script src="jquery/jquery-2.1.1.js"></script>
	<title>main</title>
</head>
<body>
	<!-- load() 方法 -->
	<button id="btn1">点击加载</button>
	<h1>加载的内容:</h1>
	<div id="content1"></div>
</body>
</html>
Copy after login
###Next write the jQuery code. After the DOM is loaded, call the load method by clicking the button to load the content in test.html into the element with the id "content". The code is as follows: ###
<script type="text/javascript">
	$(function(){
		// load(url)方法
		$("#btn1").click(function(){
    		$("#content1").load("test.html")//单击时将test.html的内容加载到当前页面上
   		})
	})
</script>
Copy after login
######Run result#### #####Before loading:###############After loading:###

Lets talk about Ajax in jQuery and explain its main methods in detail

2)筛选载入的HTML文档

上面例子是将 test.html 中的内容全部都加载到 main.html 中 id 为 ”content“ 的元素中,如果只想加载某些内容,可以使用 load( url selector ) 来实现。

注意:url 和选择器之间有一个空格。

例如只加载 test.html 中 p 标签的内容,代码如下:

<script type="text/javascript">
    $(function(){
	// load(url, selector)筛选
	$("#btn1").click(function(){
    	    $("#content1").load("test.html p")
   	})
    })
</script>
Copy after login

运行结果

Lets talk about Ajax in jQuery and explain its main methods in detail

3)传递方式

load() 方法传递方式根据参数 data 来自动指定。如果没有参数传递,则采用 GET 方式,反之,则自动转换为 POST 方式。

// load(url,fn)方法,无参数传递,GET方式
$("#btn1").click(function(){
    $("#content1").load("test.html", function(){
    	// code
    })
})

// load(url,fn)方法,有参数传递,POST方式
$("#btn1").click(function(){
    $("#content1").load("test.html", {name: "peiqi", age: "18"}, function(){
    	// code
    })
})
Copy after login

4)回调参数

对于必须在加载完成后才能继续的操作,load() 方法提供了回调函数(callback),该函数有3个参数,分别代表“请求返回的内容”,“请求状态”,“XMLHttpRequest对象”,代码如下:

$("#content1").load("test.html p",function(responseText,textStates,XMLHttpRequest){
   //responseText:请求返回的内容
   //textStates:请求状态:success   error  notmodified  timeout4种
   //XMLHttpRequest:XMLHttpRequest对象
  });
Copy after login

注意:在 load() 方法中,无论Ajax请求是否成功,只要请求完成(complete),回调函数(callback)都会被触发。

3、.get()方法和.get() 方法和.post() 方法

load() 通常是从web服务器上获取静态的数据文件,如果需要传递一些参数给服务器中的页面,可以使用 .get()方法和.get() 方法和.post() 方法(或 $.ajax() 方法)。

注意:.get()方法和.get() 方法和.post() 方法是 jQuery 中的全局函数。

1)$.get() 方法

$.get() 方法使用 GET 方式来进行异步请求。

结构

$.get( url,[ data ],[ callback ],[ type ])
Copy after login

参数

Lets talk about Ajax in jQuery and explain its main methods in detail

应用

下面是一段评论页面的 HTML 代码,通过该段代码来介绍 $.get() 方法的使用。代码如下:

 <!-- $.get() 和 $.post() 方法 -->
<h3>评论</h3>
<p>姓名:<input type="text" name="" id="name"></p>
<p>内容:<textarea id="content2"></textarea></p>
<button id="btn2">发表留言</button>
<div id="msg"></div>
Copy after login

该段代码生成的页面如图所示:

Lets talk about Ajax in jQuery and explain its main methods in detail

将姓名和内容填写好后,就可以提交评论了。

a.首先需要确定请求的 URL 地址。

$("#btn2").click(function(){
    $.get("test.php", data参数, 回调函数)
})
Copy after login

b.提交之前,将姓名和内容的值作为参数 data 传递给后台。

$("#btn2").click(function(){
    $.get("test.php",  {"username":$("#name").val(), "content":$("#content2").val()}, 回调函数)
})
Copy after login

c.如果服务器接收到传递的 data 数据并成功返回,那么就可以通过回调函数将返回的数据显示到页面上。

$.get() 方法的回调函数只有两个参数

function(){
  //data:返回的内容,可以是XML文档,json文件,XHML片段等等
  //textStatus:请求状态:success  error  notmodified timeout 4种
}
Copy after login

d. data 参数代表请求返回的内容,textStatus 参数代表请求状态,而且回调函数只有当数据成功(success)后才能被调用( load() 是不管成功还是失败都被调用 )。

// $.get()方法
$("#btn2").click(function(){
    $.get("test.php", {"username":$("#name").val(),"content":$("#content2").val()}, function(data,textStatus){
    	if(textStatus=="success"){ //success
    		// code
    		$(data).appendTo("#msg")
    	}
    },
    "html")//type
})
Copy after login

e.运行结果

Lets talk about Ajax in jQuery and explain its main methods in detail

2)$.post() 方法

它与 $.get() 方法的结构和使用方式都相同,不过之间仍然有以下区别:

a. GET 方式会将参数跟在 URL 后进行传递且数据会被浏览器缓存起来,而 POST 方式则是作为 HTTP 消息的实体内容(也就是包裹在请求体中)发送给服务器,由此可见 POST 方式的安全性高于 GET 方式。

b. GET 方式对传输的数据有大小限制(通常不能大于2KB),而 POST 方式理论上大小不限制。

c. GET 方式与 POST 方式传递的数据在服务器端的获取不相同。在 PHP 中,GET 方式的数据可用 "\_GET\[\]" 获取,而 POST 方式可以用 "_POST[]" 获取。2种方式都可用 "$_REQUEST[]" 来获取。

d. GET 方式的传输速度高于 POST 方式。

由于 POST 和 GET 方式提交的所有数据都可以通过 $_REQUEST[] 来获取,因此只要改变jQuery函数,就可以将程序在 GET 请求和 POST 请求之间切换,代码如下:

// $.post()方法
$("#btn2").click(function(){
	$.post("test.php", {"username":$("#name").val(),"content":$("#content2").val()}, function(data,textStatus){
    	if(textStatus=="success"){ //success
    		// code
    		$(data).appendTo("#msg")
    	}
    },
    "html")//type
})
Copy after login

另外,当 load() 方法带有参数传递时,会使用 POST 方式发送请求。因此也可以使用 load() 方法来完成同样的功能,代码如下:

$("#btn2").click(function(){
	$("#msg").load("test.php", {
    	"username":$("#name").val(),
        "content":$("#content2").val()
    });
})
Copy after login

4、.getScript()方法和.getScript() 方法和.getJson() 方法

1)$.getScript() 方法

有时候,在页面初次加载时就获取所需的全部 JavaScript 文件是完全没有必要的。虽然可以在需要哪个 JavaScript 文件时,动态创建

$(document.createElement("script")).attr("src", "test.js").appendTo("head");
//或者
$("<script type=&#39;text/javascript&#39; src=&#39;test.js&#39; />").appendTo("head");
Copy after login

但这种方式并不理想。jQuery 提供了 $.getScript() 方法来直接加载 js 文件,与加载一个 HTML 片段一样简单方便,并且不需要对 JavaScript 文件进行处理,JavaScript 文件会自动执行。

结构

 $.getScript( url , fn ); 
 //url:请求地址
 //fn:回调函数
Copy after login

应用
新建一个 nowDate.js 文件,获取当前日期,代码如下:

function getNowDate(){
    var date = new Date
    return date;
}
Copy after login

点击“获取当前时间”按钮时 ,显示最新时间日期,代码如下:

//HTML代码
<!-- $.getScript() 方法 -->
<button id="btn3">点击获取时间</button>
<div id="message1"></div> 
    
//jQuery代码
// $.getScript()方法
$("#btn3").click(function(){
    $.getScript("nowDate.js", function(){
    	var date1 = getNowDate(); //调用nowDate.js中的getNowDate()方法获取日期
    	var txtHtml= "<div>"+ date1 + "</div>";
    	$("#message1").html(txtHtml);
    })
})
Copy after login

运行结果

加载前:

Lets talk about Ajax in jQuery and explain its main methods in detail

加载后:

1Lets talk about Ajax in jQuery and explain its main methods in detail

2)$.getJSON() 方法

.getJSON()方法用于加载JSON文件,与.getJSON() 方法用于加载JSON文件,与.getScript() 方法的用法相同。

结构

$.getJSON( url , fn);
//url:请求地址
//fn:回调函数
Copy after login

应用

新建一个 test.json 文件,代码如下:

{
    "helen":{
	"sex":"woman",
	"age":18,
	"weight":"50kg",
	"height":"165cm"
    },
    "peter":{
	"sex":"man",
	"age":28,
	"weight":"65kg",
	"height":"185cm"
    }
}
Copy after login

新建一个 HTML 文件,代码如下:

<!-- $.getJSON() 方法 -->
<button id="btn4">点击加载JSON文件</button>
<div id="message2"></div>
Copy after login

当点击加载按钮时,页面上看不到任何效果,可以在控制台查看,代码如下:

// $.getJSON()方法
$("#btn4").click(function(){
    $.getJSON("test.json", function(data){
    	console.log(data); //控制台输出返回的数据
    })
})
Copy after login

控制台输出如图:

1Lets talk about Ajax in jQuery and explain its main methods in detail

以上虽然函数加载了 JSON 文件(test.json),但是并没有告知 JavaScript 对返回的数据如何处理,所以在回调函数里我们可以处理返回的数据。

通常我们需要遍历我们得到的数据,虽然这里我们可以使用传统的for循环,但是我们也可以通过 .each(),可以用来遍历对象和数组,.each(),可以用来遍历对象和数组,.each() 函数是以一个数组或者对象为第1个参数,以一个回调函数作为第2个参数,回调函数拥有两个参数,第1个为对象的成员或者数组的下标,第2个位对应变量或内容,代码如下:

// $.getJSON()方法
$("#btn4").click(function(){
    $.getJSON("test.json", function(data){
    	console.log(data); //控制台输出返回的数据

	// 对返回的数据做处理
    	var txtHtml = "";
    	$.each(data, function(index, item){
    	    txtHtml += "<div><h4>"
    		    + index + ":</h4><ul><li>sex:"
    		    + item["sex"] + "</li><li>age:"
    		    + item["age"] + "</li><li>weight:"
    		    + item["weight"] + "</li><li>height:"
    		    + item["height"] + "</li></div>";
    	    })
    			
    	    $("#message2").html(txtHtml);
    })
})
Copy after login

效果如图:

加载前:

1Lets talk about Ajax in jQuery and explain its main methods in detail

加载后:

1Lets talk about Ajax in jQuery and explain its main methods in detail

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of Let's talk about Ajax in jQuery and explain its main methods in detail. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template