Principle: 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.
Personal Understanding:
It is to dynamically register a function a (data) on the client, and then upload the function name to the server. The server returns a ({/* json */}) to run on the client, in this way, function a (data) of the client is called to implement cross-origin.
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W // dtd xhtml Transitional // EN" http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd ">
<Html xmlns = "http://www.worg/xhtml">
<Head>
<Title> Test Jsonp </title>
<Script src = "http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Function jsonpCallback (result)
{
$. Each (result. items, function (I, item ){
$ ("If (I = 3) return false;
});
}
</Script>
</Head>
<Body>
<Script type = "text/javascript" src = "http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback = jsonpCallback "> </script>
</Body>
</Html>
JQuery solution:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W // dtd xhtml Transitional // EN" http://www.worg/TR/xhtmlDTD/xhtmltransitional.dtd ">
<Html xmlns = "http://www.worg/xhtml">
<Head>
<Title> Test Jsonp </title>
<Script src = "http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Function (){
$. GetJSON ("http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback =? ", Function (data ){
$. Each (data. items, function (I, item ){
$ ("If (I = 3) return false;
});
});
});
</Script>
</Head>
<Body> </body>
</Html>
Jquery's jsoncallback is dynamically generated and the real request server address: http://api.flickr.com/services/feeds/photos_public.gne? Tags = cat & tagmode = any & format = json & jsoncallback = jsonp00004058545738