Using jsonp for cross-origin access under jquery _ jquery

Source: Internet
Author: User
Cross-origin access of the client can be implemented through the jsonp method. jquery provides cross-origin access methods, and jQuery. ajax () supports cross-origin access through get. Of course, cross-origin processing is required on the server. The Code is as follows:


$. Ajax ({
Async: false,
Url: '', // cross-origin URL
Type: 'get ',
DataType: 'jsonp ',
Jsonp: 'jsoncallback', // default callback
Data: mydata, // request data
Timeout: 5000,
BeforeSend: function () {// jsonp mode this method is not triggered. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event.
},
Success: function (json) {// call back function pre-defined by jquery on the client. After obtaining json data on the Cross-origin server, the callback function is dynamically executed.
If (json. actionErrors. length! = 0 ){
Alert (json. actionErrors );
}

},
Complete: function (XMLHttpRequest, textStatus ){

},
Error: function (xhr ){
// Jsonp mode. This method is not triggered.
// Handle request errors
Alert ("request error (Check related network conditions .)");
}
});



The Code is as follows:


$. GetJSON (url + "? Callback =? ",
Function (json ){

});


This method is an advanced encapsulation of the preceding example $. ajax.

On the server side, obtain the callback parameter (for example, jsonp *****) to obtain
Then return the following code: "jsonp ***** (" + json array to be returned + ")";
Jquery will dynamically load and call this through the callback method: jsonp ***** (json array );
This achieves the purpose of cross-Origin data exchange.

JSONP is a Script Injection action, so it also has certain security risks.

Note: jquey does not support cross-origin post.
Reference: http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/
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.