Overview and examples of JQuery's Ajax cross-origin request principles

Source: Internet
Author: User

Today, remote data loading and page rendering are required in the project, and ajax cross-origin requests are not realized until the development stage. I vaguely remember that Jquery has proposed a solution for ajax cross-origin requests, so I immediately pulled out the Jquery API for research and released
JQuery provides two solutions for Ajax cross-origin requests, but they only support the get method. They are JQuery. ajax jsonp and jquery. getScript.

What is jsonp format? Original API: If the obtained data file is stored on a remote server (the domain name is different, that is, cross-Origin data retrieval), The jsonp type is required. If this type is used, a query string parameter callback =? will be created? This parameter is added after the request URL. The server should add the callback function name before the JSON data to complete a valid JSONP request. This means that the remote server needs to process the returned data and return a callback (json) data according to the callback parameter submitted by the client, the client will process the returned data in script Mode to process json data. JQuery. getJSON also supports jsonp data calling.

Sample Code for calling the client JQuery. ajax:Copy codeThe Code is as follows: $. ajax ({
Type: "get ",
Async: false,
Url: "http://www.xxx.com/ajax.do ",
DataType: "jsonp ",
Jsonp: "callbackparam", // parameters of the function name used by the server to receive callback calls
JsonpCallback: "success_jsonpCallback", // callback function name
Success: function (json ){
Alert (json );
Alert (json [0]. name );
},
Error: function (){
Alert ('fail ');
}
});

Sample Code of the data returned by the server:Copy codeThe Code is as follows: public void ProcessRequest (HttpContext context ){
Context. Response. ContentType = "text/plain ";
String callbackFunName = context. Request ["callbackparam"];
Context. Response. Write (callbackFunName + "([{name: \" John \ "}])");
}

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.