Ajax uses code parsing and Ajax uses code parsing.
Ajax Introduction
Ajax is considered to be (Asynchronous (short for Asynchronous) JavaScript And Xml ). Currently, Ajax is a technology that allows the browser to communicate with the server without refreshing the current page.
Synchronization refers to the communication mode in which the sender sends a packet only after the receiver sends a response.
Asynchronous means that the sender sends the next packet instead of sending the response from the receiver.
Generally, you do not need to refresh the webpage to communicate with the server:
- Flash framework
- Frameset: if you use a set of frameworks to construct a webpage, you can update only one of the frameworks without disturbing the entire page.
- XMLHttpRequest: This object is an extension of JavaScript that enables the webpage to communicate with the server. Is the best choice for creating Ajax applications. In fact, Ajax is usually used as a synonym for XMLHttpRequest (XHR) objects.
Basic ajax usage
Ajax is a technology that must be used in our development. ajax is Asynchronous javascript and xml, but now we usually use json to complete data interaction, the single responsibility of ajax is Data Interaction. sending and receiving data is its core function and unique function.
The implementation of ajax depends on XMLHttpRequest. Its basic usage is as follows:
var xhr;window.XMLHttpRequest?xhr = new XMLHttpRequest():xhr = new ActiveXObject("Microsoft.XMLHTTP");xhr.open("get","demo!register.action?name=zt&age=23",true);xhr.send(null);xhr.onreadystatechange = function(){ if(xhr.readyState==4&&xhr.status==200){ alert(JSON.parse(xhr.responseText)); }}
Ajax is responsible for sending and receiving data. The basic process is as follows:
1. Get an XMLHttpRequest object
2. Send data
3. receive the data returned by the processing server
Follow the steps above to implement an asynchronous data request process. First, obtain an xhr object. In modern browsers, we can directly obtain an xhr object Through instantiation: var xhr = new XMLHttpRequest (); In IE5 and IE6, we must use ActiveXObject to obtain the xhr object: var xhr = new ActiveXObject ("Microsoft. XMLHTTP ").
Now we have obtained the xhr object. Next we will send data through xhr. xhr. open () can receive five parameters. We often use the first three parameters:
xhr.open(arg1,arg2,arg3)
Arg1 indicates that the data request method is generally get or post.
Arg2 indicates the requested server address
Arg3 indicates whether the request is synchronous or asynchronous, the outstanding feature of ajax is Asynchronization. Therefore, we generally use the asynchronous method. The third parameter is set to true (true indicates asynchronous requests. false indicates synchronous requests)
Xhr. the open () method only prepares a request. It does not communicate with the server after calling open, but starts communication with the server after calling the send () function () function parameters are sent to the server as request bodies. If we specify the request method as get in the open () function, we usually set send () to xhr. send (null). If we want to send data through the request body, we need to set the Request Method of the open () function to post and use the data we need to send as send () function parameters: xhr. send (param). After calling the send () function, communication with the server starts.
All settings for xhr should be set before the send () function:
xhr.open(...); xhr.setRequestHeader(...); xhr.overrideMimeType(...); xhr.onreadystatechange = function(){...}; xhr.send(...);
However, because xhr. onreadystatechange is an event, it can be executed after sending (). For ease of operation, we usually put the xhr settings before the send () function.
After sending (), you can use xhr. readyState and xhr. status to monitor the status of this request, if the xhr. readyState = 4 & xhr. status = 200, the request is successful:
When the request is successful, we can use xhr. responseText to obtain the data returned by the server. Note that xhr. responseText is a string.
Common ajax APIs
The above request process is the most basic request process. The xhr object also has several frequently used methods: xhr. abort (), xhr. setRequestHeader (), xhr. overrideMimeType ().
Xhr. abort (): terminates a request and directly calls it without setting parameters.
xhr.abort()
Xhr. setRequestHeader (): Set the request header to be sent:
xhr.setRequestHeader("Content-Type","application/json; charset=utf-8")
The first parameter indicates the header to be set, and the second parameter indicates the value of the header to be set. Xhr. setRequestHeader () must be in xhr. open () and xhr. between send (), otherwise an exception is thrown, and xhr. the first parameter of setRequestHeader () is case-insensitive and can be set successfully as long as we write letters, but for ease of use, we need to set it to the correct format.
Xhr. overrideMimeType (): override the Content-Type of the Response Header:
xhr.overrideMimeType('text/plain; charset=utf-8')
Xhr. overrideMimeType () must also be set before xhr. send.
JSON. parse () and JSON. stringify ()
JSON. parse () is used to convert an object to a string, and JSON. stringify () is used to convert a string to an object. When ajax is used for data interaction, the majority of returned data is a JSON string. If the server returns data to us, we need to use JSON. parse () to parse the returned data (xhr. responseText is the data returned by the server ):
xhr.onreadystatechange = function(){ if(xhr.readyState==4&&xhr.status==200){ var data = JSON.parse(xhr.responseText); }}
In the process of using post to send data, if it is not a file upload, it is also a JSON data. To successfully send the data to the background, you need to use JSON. stringify () to convert a JSON object to a string, and set Content-Type to application/json:
var sendData = {name:"zt",age:23};...xhr.setRequestHeader("Content-Type","application/json; charset=utf-8");xhr.send(JSON.stringify(sendData));
In addition, JSON. parse () and JSON. stringify () can be used to implement the deep copy function of an object:
var sendData = {name:"zt",age:23};var copyData = JSON.parse(JSON.stringify(sendData));
$. Ajax basic usage
To facilitate the use of JQ, We have encapsulated an ajax for our convenience:
$. Ajax ({type: "post", // Request Method url: "url", // request address data :"... ", // the data sent to the server contentType :"... ", // set the data sending type. If data is a json string, set it to application/json success: function (data ){...}, // The data of the callback function for successful requests can be considered as the data returned by the server error: function (){...} // callback function for request failure });
Or:
$.ajax({ type:"post", url:"url", data:"...", contentType:"...", }) .done(function(data){...}) .fail(function(){...});
The data in the callback function is a proxy of the data returned by the server and can be directly used.
To simplify our development, JQ provides some global setting functions, including $. ajaxSetup (), $. () ajaxStart (), $ (). ajaxStop (), $ (). ajaxComplete (), $ (). ajaxError (), $ (). ajaxSuccess (), $ (). ajaxSend ().
$. AjaxSetup () is used to set basic parameters such:
$.ajaxSetup({ type:"post", contentType:"application/json; charset=utf-8" });
When using $. ajax, we can directly set it like this:
$.ajax({ url:"", success:function(){...}, error:function(){...} })
Ultimately, it is equivalent:
$.ajax({ type:"post", contentType:"application/json; charset=utf-8", url:"", success:function(){...}, error:function(){...} })
$ (). AjaxStart (), $ (). ajaxStop (), $ (). ajaxComplete (), $ (). ajaxError (), $ (). ajaxSuccess (), $ (). ajaxSend () is used to set some global callback functions. For example, when submitting data, in order to prevent multiple submissions, We need to generate a loading mask when sending the request to cancel the mask after the data is sent, if we set every ajax request, it will be very troublesome. At this time, we can use the global callback function to simplify our operations:
A global event is used to generate a mask at the beginning of the request to cancel the mask when the request is complete:
$(document).ajaxStart(function(){ loadingMask.show(); }); $(document).ajaxComplete(function(){ loadingMask.hide(); });
The above is the code parsing of Ajax introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!