Ajax uses code parsing _AJAX related

Source: Internet
Author: User
Tags file upload json

Introduction to Ajax

Ajax is considered an abbreviation for (asynchronous (asynchronous) JavaScript and XML). Now, technology that allows browsers to communicate with the server without refreshing the current page is called Ajax.

Synchronization refers to the way in which the next packet is communicated after the sender sends the data and the receiver sends back the response.

Asynchronous refers to the way in which the sender sends the data, waits for the receiver to send back the response, and then sends the next packet's communication.

Methods that do not normally communicate with the server without refreshing the page:

    • Flash Frame
    • Frameset: If you use a set of frames to construct a Web page, you can update only one of the frames without disturbing the entire page
    • XMLHttpRequest: This object is an extension of JavaScript that enables Web pages to communicate with the server. is the best choice for creating Ajax applications. In fact, Ajax is often used as a synonym for XMLHttpRequest (XHR) objects.

Ajax Basic Use

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 the data interaction, Ajax responsibility is very single is the data interaction, send data receive data is its core function is the only function.

The implementation of Ajax relies on XMLHttpRequest, and its basic use 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));
}
}

  The responsibility of Ajax is to send data and receive data. Our basic use process is:

1. Get a XMLHttpRequest Object

2. Send data

3. Receive data returned by processing server

According to the above steps to implement an asynchronous request data process, first get a Xhr object, in the modern browser we can directly instantiate to get a Xhr object: var xhr = new XMLHttpRequest (); In IE6 we must use ActiveXObject to get the Xhr object: var xhr = new ActiveXObject ("Microsoft.XMLHTTP").

At this point we've got the Xhr object next is to send the data, through the Xhr.open () method to send the data, Xhr.open () can receive 5 parameters, we often use the first three:

Xhr.open (ARG1,ARG2,ARG3)

Arg1 means that the request data is typically a GET or post

ARG2 represents the server address of the request

ARG3 Indicates whether this request is synchronous or asynchronous, the salient feature of Ajax is asynchronous so we generally use asynchronous methods the third parameter is set to True (true to make asynchronous requests false to indicate synchronous requests)

The Xhr.open () method simply prepares a request that does not communicate with the server after calling open, but only after the Send () function is invoked, and the parameters of the Send () function are sent to the server as the request body. If we specify in the open () function that the requested way is to get normally we set send () to Xhr.send (null), and if we want to send data through the request body, set the request for the open () function to post while sending the data we need to send as send () function parameter: xhr.send (param), after the Send () function is invoked, the communication with the server begins.

All settings for XHR should be set before the Send () function:

 Xhr.open (...);
 Xhr.setrequestheader (...);
 Xhr.overridemimetype (...);
 Xhr.onreadystatechange = function () {...};
 Xhr.send (...);

But since Xhr.onreadystatechange is an event, it can be executed after send (), and for readability we typically place the XHR settings before the Send () function.

The status of this request can be monitored by xhr.readystate and xhr.status after send (), and the request succeeds if xhr.readystate==4&&xhr.status==200 is satisfied:

We can get the data returned by the server through Xhr.responsetext when the request is successful, and we need to note that Xhr.responsetext is a string.

Ajax Common APIs

The above request process is one of the most basic request process XHR objects There are several commonly used methods for Xhr.abort (), Xhr.setrequestheader (), Xhr.overridemimetype ().

Xhr.abort (): Terminating a request, calling directly without setting a parameter

Xhr.abort ()

Xhr.setrequestheader (): Set the sent request header:

Xhr.setrequestheader ("Content-type", "Application/json; Charset=utf-8")

The first parameter represents the header to set, and the second parameter represents the value of the header to set. Xhr.setrequestheader () must be between Xhr.open () and xhr.send (), otherwise an exception will be thrown and Xhr.setrequestheader () The first argument is that it is not sensitive to the case as long as we write a pair of letters can be set to succeed, but for readability we want to set the correct format.

Xhr.overridemimetype (): Overriding the content-type of the response header:

Xhr.overridemimetype (' Text/plain; Charset=utf-8 ')

Xhr.overridemimetype () is also set before Xhr.send ().

Json.parse () and json.stringify () use

Json.parse () is used to convert an object to a string, and json.stringify () is used to convert a string to an object. Most of the data returned in the process of using AJAX for data interaction is a JSON-formatted string, and if the server returns the data we need to use Json.parse () To resolve 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 sending data by post, if it is not a file upload and is also a JSON data transmission, to be able to successfully send to the background, you need to use Json.stringify () to convert the JSON object to a string, Also content-type to be set 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 achieve the deep copy function of an object:

var senddata = {name: "ZT", age:23};
var copydata = Json.parse (json.stringify (senddata));

$.ajax Basic Use

In order to facilitate the use of JQ for us to encapsulate an AJAX to facilitate our use:

$.ajax ({
 type: "POST",//Request method
 URL: "url",//Request address data
 : "...",//sent to the service side of the information
 contentType: "...",// Set the type of data to send if it is a JSON string this is set to Application/json
 success:function (data) {...},//request successful callback function data can be seen as the server returned
 error:function () {...} Request failed callback function
 });

Or:

$.ajax ({
 type: "Post",
 URL: "url",
 data: "...",
 contentType: "...",
 })
 . Done ( function (data) {...})
 . Fail (function () {...});

The data in the callback function is a proxy for the database returned by the server and can be used directly.

To simplify our development JQ provides some global setup functions including $.ajaxsetup (), $. () Ajaxstart (), $ (). Ajaxstop (), $ (). Ajaxcomplete (), $ (). Ajaxerror (), $ (). Ajaxsuccess (), $ (). Ajaxsend ().

$.ajaxsetup () is used to set basic parameters such as:

$.ajaxsetup ({
 type: Post),
 contentType: "Application/json; Charset=utf-8 "
 });

We can set this up directly when using $.ajax:

 $.ajax ({
 URL: "",
 success:function () {...},
 error:function () {...}}}
 )

Ultimately equivalent to:

 $.ajax ({
 type: Post),
 contentType: "Application/json; Charset=utf-8 ",
 URL:" ",
 success:function () {...},
 error:function () {...}}
 )

$ (). Ajaxstart (), $ (). Ajaxstop (), $ (). Ajaxcomplete (), $ (). Ajaxerror (), $ (). Ajaxsuccess (), $ (). Ajaxsend () are used to set some global callback functions. For example, in order to prevent multiple submissions when submitting data we need to generate a loading mask when sending the request, and then cancel the mask after the data is sent. If we set it up once every time an AJAX request is made, we can use the global callback function to simplify our operations:

Use global events to generate a mask at the start of a request to suppress the mask upon completion of the request:

$ (document). Ajaxstart (function () {
 loadingmask.show ();
 });
 $ (document). Ajaxcomplete (function () {
 loadingmask.hide ();
 });

The above is a small set of Ajax to introduce the use of code analysis, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.