Home > Web Front-end > JS Tutorial > jquery's ajax cross-domain request principles and examples_jquery

jquery's ajax cross-domain request principles and examples_jquery

WBOY
Release: 2016-05-16 16:49:29
Original
1083 people have browsed it

Today, in the project, I needed to load remote data and render the page. I didn’t realize the problem of ajax cross-domain request until the development stage. I vaguely remembered that Jquery mentioned a solution to ajax cross-domain request, so I immediately dug out Jquery’s The API came out for research and found that
JQuery has two types of solutions for Ajax cross-domain requests, but both only support the get method. They are JQuery's jquery.ajax jsonp format and jquery.getScript method.

What is jsonp format? API original text: If the obtained data file is stored on a remote server (with different domain names, that is, cross-domain data acquisition), you need to use the jsonp type. Using this type creates a query string parameter callback=? which is appended to the requested URL. The server should add the callback function name before the JSON data 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 according to the callback parameters submitted by the client, and the client will use script to process the returned data to process the json data. deal with. JQuery.getJSON also supports the jsonp data method call.

Client-side JQuery.ajax calling code example:

Copy code The code is as follows:

$.ajax({
type : "get ",
async:false,
url : "http://www.xxx.com/ajax.do",
dataType : "jsonp",
jsonp: "callbackparam",// The parameter used by the server to receive the function name of the callback call
jsonpCallback: "success_jsonpCallback", //The function name of the callback
success: function(json){
alert(json);
alert( json[0].name);
},
error:function(){
alert('fail');
}
});

Sample code for data returned by the server:

Copy code The 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 labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template