jquery Ajax cross-domain request

Source: Internet
Author: User

This is the resolution of the JQuery API documentation for cross-domain requests: If the obtained data file resides on the remote server (the domain name is different, that is, the data is obtained across domains), the JSONP type is required. With this type, a query string parameter callback= is created? , this parameter is appended to the URL of the request. The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request. if you want to specify the parameter name of the callback function instead of the default callback, you can set the JSONP parameter of the $.ajax ().

We use demo to ponder the above analysis:

$.ajax ({type:"Get", URL:"http://www.yourdomain.com/site/test",//the address that is actually generated at the time of the visit is:Http://www.yourdomain.com/site/test?callback=jsonpCallback&id=1Data: {ID:1}, DataType:"Jsonp", Success:function (data) {alert (Data.statu); }, Error:function (Xmlhttprequest,textstatus,errorthrown) {alert (xmlhttpreques                        T.status);                        alert (xmlhttprequest.readystate);                    alert (textstatus); }                });

This is one of the simplest cross-domain access requests. Well, to say the difference from ordinary Ajax. First, the address is actually accessed at:

http://www.yourdomain.com/site/test?callback= random number &id=10. Refer to the API definition:
With this type, a query string parameter callback= is created? , this parameter is appended to the URL of the request.

This random number is automatically generated by jquery. In the case of the JSONP type, the resulting URL is the same.

Next, look behind the scenes:

The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request.

This is the code for the server (C # MVC):

        [HttpGet]        publicstring Test (stringstring  id)        {             return " ("{\" statu\ ":"}); " ;        }

A valid JSONP request that requires a callback function name before the JSON data. The callback function name is the value passed by callback in the above URL. At this point the value passed by the server is:

jquery18308788135794457048_1419557549884 ({"statu":"1"});

Alert (Data.statu), and correctly outputs "1". Some people will say that there is a callback function before the JSON data name, do not have to deal with the normal output Data.statu?? Yes, this is JSONP.

At this point, the first 3 sentences of the API have been resolved clearly. That's the last sentence left. The above callback are randomly generated by jquery, and the callback function name is fixed to callback if the user wants to define it himself. This will take the last word.

If you want to specify the parameter name of the callback function instead of the default callback, you can set the JSONP parameter of the $.ajax ().

The AJAX code is as follows:

$.ajax ({type:"Get", URL:"http://www.yourdomain.com/site/test",//the address that is actually generated at the time of the visit is:Http://www.yourdomain.com/site/test?mycallback=jsonpCallback&id=1Data: {ID:1}, DataType:"Jsonp", Jsonp:"Mycallback", Jsoncallback:"Jsonpcallback", Success:function (data) {alert (Data.statu); }, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert (xmlhttprequest.status);
alert (xmlhttprequest.readystate);
alert (textstatus);
} });

See the code should understand it. The Jsonp property is set to pass the past request parameter name. The Jsoncallback property is a custom pass past parameter. The URL that is actually accessed at this time is:

Http://www.yourdomain.com/site/test?mycallback=jsonpCallback&id=1

The next step is not to elaborate. Background Receive code:
        [HttpGet]        publicstring Test (stringstring  id)        {             return " ("{\" statu\ ":"}); " ;        }

The data received:

Jsonpcallback ({"statu":"1"});

The point is that. The JSONP type AJAX only supports get requests, and the POST request has been tested and is not possible.

At this point, the parsing of the API is fully parsed.

Next, is the zigzag version.

function Test () {alert ("I am back~~"); } $.ajax ({type:"Get",                    //Async:false,Url:"http://www.yourdomain.com/site/test",//in fact, the address generated during the visit is: test?callback=jsonpcallback&id=10Data: {ID:Ten}, Cache:false,//Default Value TrueDataType:"Jsonp", Jsonp:"Callback",//The parameter name passed to the request handler or page to obtain the name of the JSONP callback function (default: Callback)Jsonpcallback:"Test",                    //Custom JSONP callback function name, default to jquery auto-generated random function name//if the JSONP callback function is customized here, the callback function works first, followed by the success functionsuccess:function (data) {alert (Data.statu); //alert (json.message);}, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {                        alert (xmlhttprequest.status);                        alert (xmlhttprequest.readystate);                    alert (textstatus); }                });

If you pass past the Jsonpcallback parameter as a JS function, it is also possible. After a successful callback, the Jsonpcallback function is called first, followed by the success function. That is, alert ("I am back~"), followed by alert (10).

Note: The Jsonpcallback property cannot be an anonymous function. that cannot be as follows:

$.ajax ({type:"Get",                    //Async:false,Url:"Http://www.yourdomain.com/site/test4",//in fact, the address generated during the visit is: test4?callback=undefinedk&id=10Data: {ID:Ten}, Cache:false,//Default Value TrueDataType:"Jsonp", Jsonp:"Callback",//The parameter name passed to the request handler or page to obtain the name of the JSONP callback function (default: Callback)jsonpcallback:function () {},//Custom JSONP callback function name, default to jquery auto-generated random function name//if the JSONP callback function is customized here, the callback function works first, followed by the success functionsuccess:function (data) {alert (Data.statu); //alert (json.message);}, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {                        alert (xmlhttprequest.status);                        alert (xmlhttprequest.readystate);                    alert (textstatus); }                });

In that case, it will return normally. But run the anonymous function first, and then run the error function.

jquery Ajax cross-domain request

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.