Today in the project to do the remote data loading and rendering the page, until the development phase to realize the problem of Ajax Cross-domain request, vaguely remember jquery has mentioned an AJAX Cross-domain request solution, so immediately out of the jquery API to study, hair
jquery has two types of solutions for Ajax Cross-domain requests, but only the get way is supported. Is the jquery jquery.ajax jsonp format and the Jquery.getscript method respectively.
What is the JSONP format? Original API: If you get a data file that resides on a remote server (the domain name is different, that is, cross domain to get data), you need to use the JSONP type. Using this type, a query string parameter is created callback=? , this parameter is appended to the URL of the request. The server side should precede the JSON data with the callback function name in order to complete a valid JSONP request. This means that the remote server needs to process the returned data and return a callback (JSON) data based on the callback parameters submitted by the client, and the client will process the returned data in a script to handle the JSON data. The Jquery.getjson also supports the JSONP data method invocation.
Sample call code for client Jquery.ajax:
Copy Code code as follows:
$.ajax ({
Type: "Get",
Async:false,
URL: "Http://www.xxx.com/ajax.do",
DataType: "Jsonp",
JSONP: "Callbackparam",//The parameter of the function name used by the server to receive the callback call
Jsonpcallback: "Success_jsonpcallback",//callback's function name
Success:function (JSON) {
alert (JSON);
alert (json[0].name);
},
Error:function () {
Alert (' fail ');
}
});
Sample code for server-side return data:
Copy Code code as follows:
public void ProcessRequest (HttpContext context) {
Context. Response.ContentType = "Text/plain";
String Callbackfunname = context. request["Callbackparam"];
Context. Response.Write (Callbackfunname + "([{name:\" john\ "}])");
}