To elaborate on Ajax

Source: Internet
Author: User
Tags script tag tag name

One, the Ajax in JS

Ajax (Asynchronous Javascript and XML) is asynchronous JavaScript and XML, as the name implies, this technique is irrelevant to our current page refresh, Because it is asynchronous, in the absence of Ajax, if we go to request the data in the database will be the current page to refresh, the most common you can think of our form Validation section, previously filled out all the forms to a one-time verification, such as the registration interface, you fill the wrong to refresh the page to start again, so, Now with Ajax you can complete a validation with a form and the page will not refresh.

For Ajax, his core technology is the object, its whole process is actually the current page continue to work, it will open a space-time tunnel and the current interface to work together, just like two parallel space, its entire process can be summed up to create a XMLHttpRequest object, and then connect to the server, Send the request, and finally accept the data sent by the server, well, XMLHttpRequest is a very magical object that allows us to connect the front and back end, we first create a XMLHttpRequest object

var xhr =null;        if (window. XMLHttpRequest) {            xhr = new XMLHttpRequest ();        } else{            xhr = new ActiveXObject (' microsoft.xmlhttp ');        } Here is for the compatibility of IE browser processing, in IE, our XMLHttpRequest object becomes activeobject, and inside the parameters are not less, ie is so stubborn

When we have a xhr instance, we can send the request to the database, here we take a look at the method we need to use, the open () method is to establish a front-end to the server request, and the Send method is to send a request to the server, that is, when we call takeout, We use the United States like the Open () method, the establishment of our contact with the store, and express brother is our Send () method, he will our delicious to send us, here we first use the Get method to do an example, in the next block we look at our two request method get and SE difference:

var url = "Index.php?id=1", Xhr.open (' Get ', url, ' true '),//open has three parameters, the first parameter is used to specify whether to commit using GET or post, the second parameter is to specify the URL address to send, The third parameter specifies whether to use async, and the third parameter defaults to True;xhr.send ();

This is the way we've sent a request to index.php using GET, and we're going through the arguments for "id=1"; so let's take a look at the difference between get and post, get and post are used to send data, literally, get (get) is to get things from the database request way, and post (send) is to send data to the server, and post data transmission is encrypted, post data placed in the request body, and get only the request header, no request body, so get can also pass to the database a small amount of data, The way to send is after the URL address with? To do, if there are multiple parameters with & separated, we first look at the use of post:

var url = "index.php"; var data = "Id=1"; Xhr.open (' Post ', url,true); Xhr.setrequestheader (' Contenttype ', ' application/ x-www-form-urlencoded ')//post request needs to set the request header information Xhr.send (data);

  

So now we have simply sent the request to the server side, our normal process is that the server will be based on our parameters or the results of its own operation to return data to us, here we do not have to send to the database parameters, for example, the server has an array ["0": "Apple", "1 ":" Orange "," 2 ":" Banana "], now if we do not pass the argument, the server will return this array to us, if we wear a id=1, then the data returned is an orange, we have to understand is that we pass the parameters and data for us to obtain the data is only an auxiliary role, What really works is the internal structure of the server, then we now send a request, we face a problem, how do we tell if the request is sent successfully and the server is processing our request, and if the server responds, it returns to our data how to get it?

OK, let's see, there is a readystate attribute on the XHR instance that represents the state of the current XMLHttpRequest:

0: The request was not issued (before calling Open)

1: The request has been established but has not yet been issued

2: The request has been issued

3: The request is being processed

4: The request has been processed by the server and is ready accordingly

Whenever the readystate state changes, the onreadystatechange () function is called, so we can judge the corresponding state in the onreadystatechange and get the corresponding return data, when readystate is 4 o'clock, On behalf of our request was successfully executed by the server, but we also need to determine whether the data we need is successfully returned? We also have a status attribute, which also has a number of state codes representing different response states, of which 200 represents a successful response. And the response data is returned to the front-end:

Xhr.onreadystatechange = function () {     if (xhr.readystate = = 4) {//request has been successfully processed         if (xhr.status = = 200) {// Successfully received a response from the server             //The data returned here is processed        }}    }

After the response, ResponseText represents the corresponding data in the form of a string, Responsexml represents the response data in the form of XML, Getallresponseheader (): Gets all the response headers, here we write an AJAX request completely:

var xhr =null;    if (window. XMLHttpRequest) {        xhr = new XMLHttpRequest ();    } else{        xhr = new ActiveXObject (' microsoft.xmlhttp ');    }    var url = "Index.php?id=1";    Xhr.open (' Get ', url, ' true '),//open has three parameters, the first parameter is used to specify whether to commit using GET or post, the second parameter is to specify the URL address to send, the third parameter specifies if async is used, and the third parameter is true by default;    Xhr.send ();    Xhr.onreadystatechange = function () {        if (xhr.readystate = = 4) {//request has been successfully processed            if (xhr.status = = 200) {// Successfully received response from Server                   alert (responsetext);}}                }    The corresponding backend will use PHP to implement a small demo

  

Two, XML and JSON

After we have finished sending the request and obtained the data from the backend, we should think about it further, then can I specify the data from the backend? Then there is our JSON and XML data format, both of which we format the front-end and back-end data transfer, Well, let's take a look at the xml,xml data. Actually you can also think of as our HTML tag, but it is the label that we can customize, you can give its tag name to make very meaningful, so it is very convenient for you to use:

1 < China>2     <Provincename= ' Henan '>3      < City>Zhengzhou</ City>4     </Province>5     6 </ China>7 //This is a simple XML format of data, we can use this data to manipulate the DOM object using JS method,8XML data must have a root node

Another commonly used data format is JSON, JSON is a language-independent data format, that is, it can be used in many languages, not limited to a particular language, and it is less than the amount of code in XML, and easy to parse, XML has a large amount of data analysis inconvenience , but because JSON appears late, so now most people still use XML, helpless and many back-end data are stored in XML, JSON format somewhat similar to our JavaScript object literal:

1 {"Name": "James",2  "hobby": "Basketball",3    "son": {"Littleson": " Er "," Bigson ":" San "}4}//This is a simple JSON format data, JSON data code is small, but the readability of 5 or XML looks more pleasing to the eye, But the code block that people look at is exactly what the machine likes.

Get the data, we also need to parse to be able to use, compared to XML some DOM-like parsing method, XML parsing in JS is the longest parsing method is Json.parse (), and the JS object into a JSON object we use Json.stringify () , of course, there are many differences between JSON and XML, here I present a summary of the predecessor, a very detailed summary: http://www.cnblogs.com/SanMaoSpace/p/3139186.htm

Third, Ajax in jquery

So we have seen Ajax in the application of JS, jquery is known as the most powerful JS packaging library, how can not be the AJAX package? Let's take a brief look at the Ajax package for the jquery source code:

Its approximate position is around 7,000 lines jquery.extend ({    ajax:function (URL, options) {}});//From this approximate form, we can see that Ajax is encapsulated in the jquery tool method, is directly encapsulated in jquery, so the call is directly using the jquery function, so our call to it is $.ajax ();

So let's write a simple post-request method for jquery:

1 $.ajax ({2 type: "POST",//Request method3 URL: "a.php",//server's link address4 dataType: "JSON",//format for transmitting and receiving data5 data:{6 Username: "James",7 Password: "123456"8                     },9 success:function (data) {//function called when data is accepted successfullyTen console.log (data);//data returned to the server One                     }, A error:function (Request) {//function called when request data fails - alert ("Error occurred:" +request.status); -                     } the});

With the post request way of example, presumably get the way to the wording of everyone, look at the example of jquery, is not the feeling is very simple, a lot of compatibility with the processing of jquery has helped us do, is this feel.

Four, cross-domain requests

In the example above, we use AJAX to request both local and our homologous files, because JavaScript is designed to not allow cross-domain requests for security reasons, so what is a cross-domain?

The above is our different sources of the situation, encountered this situation, and then to use the above-mentioned way is not, then how can we solve the cross-domain request problem? JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to solve data access problems in mainstream browsers, because HTML <script> element tags can dynamically load data from other sources, so we can leverage < Script> tags to implement cross-domain requests, this approach becomes JSONP, of course, JSONP and JSON is not the same thing, JSON is a transmission format of data, and JSONP is a cross-domain request way, simple understanding is:

For Jsonp this cross-domain request method, we first write an example, and then follow this example to slowly introduce:

<! DOCTYPE html>

When we run the top example, open developer mode in Chrome, click network-> View Request package, click Response, and we can see:

Yes, at this time, the remote database returned to us a large string of data, careful observation, it is not difficult to find that the format of this string of data is weather (data); Gee, isn't this a weather function call? Yes, yes, our database is returning a function call, and looking at it, The argument behind the URL address in our script is _jsonp=weather, and we change it to Tianqi found to be a tianqi (). Oh, the original _JSONP parameter is the function name returned to us by the specified server, Then the parameter in the function is the data that the server returns to us, then we also found that the browser has an error:

So that is to say that our code does not weather this function, plus the above explanation, we should then go directly to the mechanism of its operation, after the execution of cross-domain calls in the script, will call the weather function directly, So at this point we're going to write a weather function for the script to execute, then the arguments in the weather function are the data we want, we can use our data directly in the weather function, and here's a little bit, Jsonp only Get request method, that is, pass the parameter to the URL behind, and the data transmission format is JSON,

<script> function    Weather (data) {///callback function        console.log (data);    } </script><script src= "Http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=weather &code=111111 "></script>

Then we can see the result:

Here we use JSONP call data, we need to understand the format of the background data, because we have to pass some parameters to get data, so the front end is not split, then we can also use the dynamic loading script tag method to click the button to get the data

function Createscript () {        var script = document.createelement (' script ');        var url    = "http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=weather&code=";        SCRIPT.SRC = Url+params;        Document.body.appendChild (script);    } Using this function, you can load the data dynamically.

So let's look at the use of Jsonp in jquery:

$.ajax ({                type: ' Get ',                URL: Weather forecast interface,                async: ' true ',//Whether it is an asynchronous call to                DataType: ' Jsonp ', specifying the mode of data transfer                JSONP: ' Jsoncallback ',     ///callback function name key value can be omitted                jsonpcallback: ' XBox ',       //callback function name can be omitted                success:function (data) {                   ///successful post execution function, data is the function value we want to get                },                error: Function  () {                     /////Failure Execution               }

Get the data we can display in the HTML tag, with this asynchronous call way, we can go to do something very fun, what weather forecast, express query, music player, are not easy, of course, cross-domain calls There are many kinds, but I use a little more on the JSONP, the other method will not mention , the article may have some knowledge points are missing, after all, is a small summary of their own, I hope to be a little help to everyone.

Reprint {Study will make you young forever}

To elaborate on Ajax

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.