I used to blog about JSONP in the past. For example, my WordPress weather plug-in calls weather data through JSONP. Today I will talk about cross-origin application through JSONP ~
What is JSONP?
JSONP is JSON with Padding. Due to the same-origin policy restrictions, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. For cross-origin requests, we can use the html script tag to perform cross-origin requests, and return the script code to be executed in the response, where javascript objects can be directly transmitted using JSON. This cross-origin communication method is called JSONP.
For the above explanation, we can simply understand it as follows: JSONP is a cross-domain communication method that can be implemented through JavaScript files. For example, the popular search tips of various websites and the sogou cloud Input Method
Note: The JSONP server code must take full security measures.
The simplest JSONP
Var JSONP = document. createElement ("script ");
// FF: onload IE: onreadystatechange
JSONP. onload = JSONP. onreadystatechange = function (){
// Onreadystatechange, only IE
If (! This. readyState | this. readyState = "loaded" | this. readyState = "complete "){
Alert ($ ("# demo" example .html ());
JSONP. onload = JSONP. onreadystatechange = null // enable memory to prevent IE memory leaks
}
}
JSONP. type = "text/javascript ";
JSONP. src = "http://a.pojaaimg.cn/2010/js/jquery.js ";
// Add a js file after the head
Document. getElementsByTagName ("head") [0]. appendChild (JSONP );
Simple Explanation: we create a script, specify its src and other attributes, and insert it to the head for execution.
Suggestion: onload and onreadystatechange should be written before the src value assignment to prevent loading js from being too fast and not assigning values to onload and onreadystatechange (Image objects have such phenomena in IE)
JSONP instance
We can first define a function to execute the data returned by JSONP, and then pass this function to the background through src of JSONP for processing and return executable functions. For example, the following code:
Function jsonpHandle (){
Alert ();
}
Var JSONP = document. createElement ("script ");
JSONP. type = "text/javascript ";
JSONP. src = "http://www.js8.in/jsonp.php? Callback = jsonpHandle ";
// Add a js file after the head
Document. getElementsByTagName ("head") [0]. appendChild (JSONP );
Jsonp. php code in the background:
Echo $ _ GET ["callback"]. "('hello, World ')";
Source: http://www.js8.in/548.html