Home >Web Front-end >JS Tutorial >jQuery and Ajax and serialization_jquery
About AJAX
The so-called Ajax, the full name is Asynchronous JavaScript and XML. (That is, asynchronous JS and XML)
To put it simply, it means sending and getting data without refreshing the page, and then updating the page.
Advantages of Ajax
•No plug-in support required
•Excellent user experience
•Improve the performance of web applications
•Reduce the burden on servers and bandwidth
Disadvantages of Ajax
•Insufficient browser compatibility
• Breaks the normal functionality of the browser’s forward and back buttons
•Inadequate support for search engines
•Lack of development and debugging tools
Well, these were all shortcomings from a few years ago. Technology is developing rapidly, and these shortcomings will gradually be made up. At least it is not difficult to debug Ajax now.
The core of Ajax is the XMLHttpRequest object, which is the key to Ajax implementation.
I won’t mention the traditional examples of implementing Ajax. It’s so painful that I didn’t even remember it. I searched a lot on the Internet.
About Ajax in jQuery
$.ajax() method is the Ajax method that encapsulates the most original js.
load(), $.get(), $.post() are encapsulated $.ajax()
$.getScript() and $.getJSON() are further encapsulations.
•load() method •Use: Load remote HTML code and insert it into the DOM. It is usually used to obtain static data files. The structure is: load(url [,data] [,callback]). •url is the requested address
•data is optional and is the parameter object sent to the server
•callback is a callback function, which is called whether the request succeeds or fails
•You can even add filters to the address when loading the page
$("#resDiv").load("test.html .myClass");//这个div里只载入test.html页面里面 样式为myClass 的元素 //举一个完整的例子 $(function(){ $("#resDiv").load("text.php",{name:"troy",textInfo:"hello"},function(responseText,textStatus,XMLHttpRequest){ //responseText:请求返回的内容 //textStatus: 请求状态:success、error、notmodiffied、timeout 4种 //XMLHttpRequest: XMLHttpRequest对象 }); });
•$.get() method •Obviously the calling method is different, so this function is a global function of jQuery. The previous methods and load() all operate on jQuery objects
•The $.get() method uses the GET method to make asynchronous requests. The structure is: $.get(url [,data] [,callback] [,type]) •The first three parameters will not be mentioned. The only difference is callback is only called if the request is successful
•The type parameter is the format of content returned by the server, including xml, html, script, json, text and _default
•Example
$("#send").click(function() $.get("get1.php" ,{ username:$("#username").val(), content:$("#content").val() } ,function(data,textStatus){ //data: 返回的内容,可以是XML文档、JSON文件、HTML片段 //textStatus: 请求状态:success、error、notmodiffied、timeout 4种 } ) })
•$.post() method •It plays the same way as the get method, but one is the get method and the other is the post method.
•$.getScript() method •Sometimes it is not necessary to obtain all scripts when the page is first loaded, so jQuery provides the getScript method to directly load js files.
•Example
$('#send').click(function(){ $.getScript('test.js',function(){ //do something 这个时候脚本已经加载了,不需要再对js文件进行处理 }); });
• $.getJSON() method • Used to load JSON files, the usage is the same as above, except that the json data is returned
$('#send').click(function(){ $.getJSON("myurl",function(data){ var html=""; $.each(data,function(commentIndex,comment){ html+=commentIndex+":"+comment['username']+";"; }) alert(html); }) }); //注意一下ecch这种玩法,同样是个全局函数。他的回调函数中,第一个参数为成员的索引,第二个为变量和内容
By the way, expand on JSONP for cross-domain access
$("#send").click(function(){ $.getJSON("http://www.某网站.com/services/getMyCmpJson?tags=car&tagmode=any&format=json&jsoncall back=?" ,function(data){ //某些操作 } ) })
//JSONP is an unofficial protocol, which uses a combination of json and 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags. It is mainly used for cross-domain web applications
•$.ajax() method •This method is the lowest level Ajax implementation of jQuery, so it is naturally more powerful and complex.
Although it has only one parameter, this parameter object contains many attributes, but they are all optional. All attributes are listed below: • url: Default current page address, you can also manually write the requested address
•type: The default is GET, you can also write POST
•timeout: Set request timeout (milliseconds)
•data: sent data
•dataType: The data type expected to be returned by the server.
•beforeSend: The function called before sending. If the function returns false, the ajax request will be canceled.
function(XMLHttpRequest){//XMLHttpRequest是唯一的参数 this;//调用本次Ajax请求时传递的options参数 }
•complete: Called after the request is completed, regardless of success or failure.
function(XMLHttpRequest,textStatus){//textStatus描述成功请求类型 this;//调用本次Ajax请求时传递的options参数 }
•success: callback function after the request is successful
function(data,textStatus){//data为成功返回的数据 this;//调用本次Ajax请求时传递的options参数 }
•error: Function called when the request fails
function(XMLHttpRequest,textStatus,errorThrown){ // textStatus为错误信息,errorThrown为捕获的错误对象,通常只有其中一个包含信息 this;//调用本次Ajax请求时传递的options参数 }
•global: Default is true. Indicates whether to trigger global Ajax events.
•Serialize elements •serialize() method •It can serialize DOM element content into string
//不仅可以序列化整个表单,也可以序列化单个元素,并且都是自动编码过的 $.post("myurl",$("#form1").serialize(),function(data,textStatus){ $("#resText").html(data); })
•serializeArray() method •It can serialize DOM element content into JSON format
•$.param() method •This is the core of the serialize method, used to serialize an array or object according to key-value pairs
var obj={a:1,b:2,c:3}; var k=$.param(obj);//输出为a=1&b=2&c=3
•Ajax global events in jQuery •ajaxStart() method: triggered when the Ajax request starts
•ajaxStop() method: triggered when the Ajax request ends
<div id="loading">加载中...</div> $("#loading").ajaxStart(function(){ $(this).show();//ajax开始请求就显示加载中 }); $("#loading").ajaxStop(function(){ $(this).hide();//ajax开始结束就隐藏加载中 });
•ajaxComplete():当Ajax请求完成就触发
•ajaxError():当Ajax请求发生就触发,捕捉到的错误可以作为最后一个参数传递
•ajaxSend():当Ajax请求发送前就触发
•ajaxSuccess():当Ajax请求成功就触发
•如果想使某个Ajax请求不受全局事件的影响,可以在$.ajax中将global属性设置为false,这个在前面已经讲过了。当然也可以在ajax请求前:
$.ajaxPrefilter(function(options){//每次发送前请求 options.global=true; })
好吧,写完了。最后顺带提一下,setTimeout("doMethod()",4000);为4s后执行doMethod这个函数。
//一个简单的定时发送功能 function updateMsg(){ $.post("myurl",{time:timestamp},function(xml){ //do something }); setTimeout("updateMsg()",4000); }