Today in the project need to do remote data loading and rendering the page, until the development stage to realize the problem of Ajax cross-domain requests, vaguely remember that jquery has mentioned an Ajax cross-domain request solution, and immediately turned out the jquery API to study, Discover that jquery has two types of solutions for Ajax cross-domain requests, but only the Get method is supported. The Jquery.ajax Jsonp format and Jquery.getscript method of jquery are respectively.
What is the JSONP format? API Original: If the obtained data file is stored on the remote server (the domain name is different, that is, cross-domain Fetch data), you need to use the JSONP type. 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. This means that the remote server needs to do the processing of the returned data, according to the callback parameters submitted by the client, return a callback (JSON) data, and the client will process the return data in script to do the JSON data. Jquery.getjson also supports JSONP data-mode invocation.
Example of calling code for client Jquery.ajax:
$.ajax ({ type: "Get", async:false, URL: "http://www.xxx.com/ajax.do", dataType: "Jsonp", JSONP: "Callbackparam",//the server is used to receive parameters of callback called function name jsonpcallback: "Success_jsonpcallback",// callback function name success:function (JSON) { alert (JSON); alert (json[0].name); }, error:function () { alert (' Fail ');} });
Sample code that returns data from the server:
public void ProcessRequest (HttpContext context) { context. Response.ContentType = "Text/plain"; String Callbackfunname = context. request["Callbackparam"]; Context. Response.Write (Callbackfunname + "([{name:\" john\ "}])");
jquery's Ajax cross-domain request solution