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!
This article refers to and quotes "Sharp JQuery" to provide a detailed explanation of jQuery-Ajax and its main methods.
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.
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.
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.
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.
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
In the picture above, layeris. o(
) 方 法 , 3layer
is
.getScript() and $.getJSON() methods.
I have previously published an article "Detailed explanation of jquery ajax-ajax() method"
For details, please click: https:/ /juejin.cn/post/70191880637043507562. 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] )
Application
测试 hello world!
- C
- C#
- C++
- Java
- .Net
- JSP
- ASP
- PHP
- Python
- ios
- Android
- Javascript
- CSS
- HTML
- XML
- VUE
- React
- Angular
- SQL
main 加载的内容:
2)筛选载入的HTML文档
上面例子是将 test.html 中的内容全部都加载到 main.html 中 id 为 ”content“ 的元素中,如果只想加载某些内容,可以使用 load( url selector ) 来实现。
注意:url 和选择器之间有一个空格。
例如只加载 test.html 中 p 标签的内容,代码如下:
运行结果
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 }) })
4)回调参数
对于必须在加载完成后才能继续的操作,load() 方法提供了回调函数(callback),该函数有3个参数,分别代表“请求返回的内容”,“请求状态”,“XMLHttpRequest对象”,代码如下:
$("#content1").load("test.html p",function(responseText,textStates,XMLHttpRequest){ //responseText:请求返回的内容 //textStates:请求状态:success error notmodified timeout4种 //XMLHttpRequest:XMLHttpRequest对象 });
注意:在 load() 方法中,无论Ajax请求是否成功,只要请求完成(complete),回调函数(callback)都会被触发。
load() 通常是从web服务器上获取静态的数据文件,如果需要传递一些参数给服务器中的页面,可以使用 .post() 方法(或 $.ajax() 方法)。
注意: .post() 方法是 jQuery 中的全局函数。
1)$.get() 方法
$.get() 方法使用 GET 方式来进行异步请求。
结构
$.get( url,[ data ],[ callback ],[ type ])
参数
应用
下面是一段评论页面的 HTML 代码,通过该段代码来介绍 $.get() 方法的使用。代码如下:
评论
姓名:
内容:
该段代码生成的页面如图所示:
将姓名和内容填写好后,就可以提交评论了。
a.首先需要确定请求的 URL 地址。
$("#btn2").click(function(){ $.get("test.php", data参数, 回调函数) })
b.提交之前,将姓名和内容的值作为参数 data 传递给后台。
$("#btn2").click(function(){ $.get("test.php", {"username":$("#name").val(), "content":$("#content2").val()}, 回调函数) })
c.如果服务器接收到传递的 data 数据并成功返回,那么就可以通过回调函数将返回的数据显示到页面上。
$.get() 方法的回调函数只有两个参数
function(){ //data:返回的内容,可以是XML文档,json文件,XHML片段等等 //textStatus:请求状态:success error notmodified timeout 4种 }
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 })
e.运行结果
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 })
另外,当 load() 方法带有参数传递时,会使用 POST 方式发送请求。因此也可以使用 load() 方法来完成同样的功能,代码如下:
$("#btn2").click(function(){ $("#msg").load("test.php", { "username":$("#name").val(), "content":$("#content2").val() }); })
4、 .getJson() 方法
1)$.getScript() 方法
有时候,在页面初次加载时就获取所需的全部 JavaScript 文件是完全没有必要的。虽然可以在需要哪个 JavaScript 文件时,动态创建
$(document.createElement("script")).attr("src", "test.js").appendTo("head"); //或者 $("").appendTo("head");
但这种方式并不理想。jQuery 提供了 $.getScript() 方法来直接加载 js 文件,与加载一个 HTML 片段一样简单方便,并且不需要对 JavaScript 文件进行处理,JavaScript 文件会自动执行。
结构
$.getScript( url , fn ); //url:请求地址 //fn:回调函数
应用
新建一个 nowDate.js 文件,获取当前日期,代码如下:
function getNowDate(){ var date = new Date return date; }
点击“获取当前时间”按钮时 ,显示最新时间日期,代码如下:
//HTML代码 //jQuery代码 // $.getScript()方法 $("#btn3").click(function(){ $.getScript("nowDate.js", function(){ var date1 = getNowDate(); //调用nowDate.js中的getNowDate()方法获取日期 var txtHtml= ""+ date1 + ""; $("#message1").html(txtHtml); }) })
运行结果
加载前:
加载后:
2)$.getJSON() 方法
.getScript() 方法的用法相同。
结构
$.getJSON( url , fn); //url:请求地址 //fn:回调函数
应用
新建一个 test.json 文件,代码如下:
{ "helen":{ "sex":"woman", "age":18, "weight":"50kg", "height":"165cm" }, "peter":{ "sex":"man", "age":28, "weight":"65kg", "height":"185cm" } }
新建一个 HTML 文件,代码如下:
当点击加载按钮时,页面上看不到任何效果,可以在控制台查看,代码如下:
// $.getJSON()方法 $("#btn4").click(function(){ $.getJSON("test.json", function(data){ console.log(data); //控制台输出返回的数据 }) })
控制台输出如图:
以上虽然函数加载了 JSON 文件(test.json),但是并没有告知 JavaScript 对返回的数据如何处理,所以在回调函数里我们可以处理返回的数据。
通常我们需要遍历我们得到的数据,虽然这里我们可以使用传统的for循环,但是我们也可以通过 .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 += ""; }) $("#message2").html(txtHtml); }) })" + index + ":
- sex:" + item["sex"] + "
- age:" + item["age"] + "
- weight:" + item["weight"] + "
- height:" + item["height"] + "
效果如图:
加载前:
加载后:
【推荐学习: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!