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 \ "}])");
}