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

青灯夜游
Release: 2022-03-15 11:12:13
forward
3007 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, . A j a x ( ) The method is j Q u # The lowest method in ##e r y , the layer 2 is . l o a d ( ) , .Ajax() method is the lowest method in jQuery, the second layer is .load(), layeris. l o a d ( ) , .get() and . p o(

)

,

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: ###
    测试 

hello world!

  • C
  • C#
  • C++
  • Java
  • .Net
  • JSP
  • ASP
  • PHP
  • Python
  • ios
  • Android
  • Javascript
  • CSS
  • HTML
  • XML
  • VUE
  • React
  • Angular
  • SQL
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:
     main 

加载的内容:

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: ###
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 标签的内容,代码如下:

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、 . g e t ( ) 方法和 .get() 方法和 .post() 方法

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

注意: . g e t ( ) 方法和 .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() 方法的使用。代码如下:

 

评论

姓名:

内容:

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、 . g e t S c r i p t ( ) 方法和 .getScript() 方法和 .getJson() 方法

1)$.getScript() 方法

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

$(document.createElement("script")).attr("src", "test.js").appendTo("head"); //或者 $("