First glance at jsonp
Jsonp is short for JSON with Padding. It is a solution for cross-origin request resources. Most of the time, we need to obtain server data on the client for operations. Generally, we use ajax + webservice to do this, but if we want to obtain the data and the current page is not a domain, the famous same-origin policy (client scripts in different domains cannot read or write resources of the other party without explicit authorization) will reject requests for security reasons, that is, we cannot directly send requests to other domains to obtain resources.
There is a books. php file in the localhot domain, which contains a script to send a get request to books. php In the test.com domain to obtain its book list resources. This is a cross-origin request resource.
Copy codeThe Code is as follows:
$. Ajax ({
Type: 'get ',
Url: 'http: // test.com/books.php'
});
The page reports an error like this: XMLHttpRequest cannot load http://test.com/books.php. Origin http: // localhost is not allowed by Access-Control-Allow-Origin.jsonp to solve this problem.
Jsonp Principle
Although there are restrictions on the same origin policy, not all HTML resources must be in the same domain. To save traffic or load speed, we use Google or Microsoft's jQuery CDN for common pages, on the page, we can write and reference jQuery.
Copy codeThe Code is as follows:
<Script type = "text/javascript"
Src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</Script>
The src attribute of iframe, img, style, script, and other elements can directly request resources from different domains. jsonp uses the script tag to request resources
Simple implementation
Localhost's books. php wants to obtain the books list of the test.com domain. The book list in the test.com domain is stored in books. xml.
Test.com/books.xml
Copy codeThe Code is as follows:
<? Xml version = "1.0"?>
<Books>
<Book name = "JavaScript: The Defiitive Guide" publisher = "O 'Reilly Media, Inc.">
<Author> David Flanagan </author>
</Book>
<Book name = "PHP anf MySQL Web Development" publisher = "Perason Education">
<Author> Luke Welling </author>
<Author> Laura Thomson </author>
</Book>
<Book name = "HTTP: The Defiitive Guide" publisher = "O 'Reilly Media, Inc.">
<Author> David Courley </author>
<Author> Brian Totty </author>
</Book>
</Books>
Obviously, JavaScript cannot directly obtain books. xml. In test.com, a mechanism is required to convert xml into json (that is, why jsonp is called). In fact, like ajax, the returned data is not necessarily in json format, json), and dynamically concatenate a javascript CALL statement to return the result. In this example, the php page is directly spliced.
Test.com/bookservice.php
Copy codeThe Code is as follows:
<? Php
$ Path = $ _ SERVER ["DOCUMENT_ROOT"]. '/books. xml ';
$ Json = json_encode (simplexml_load_file ($ path ));
$ CallbackFn = $ _ GET ['callback'];
Echo "$ callbackFn ($ json );";
?>
In this way, the content of the xml file is converted into a json object.
Copy codeThe Code is as follows:
{"Book ":[
{"@ Attributes": {"name": "JavaScript: The Defiitive Guide", "publisher": "O 'Reilly Media, Inc. "}," author ":" David Flanagan "},
{"@ Attributes": {"name": "PHP anf MySQL Web Development", "publisher": "Perason Education"}, "author": ["Luke Welling ", "Laura Thomson"]},
{"@ Attributes": {"name": "HTTP: The Defiitive Guide", "publisher": "O 'Reilly Media, Inc. "}," author ": [" David Courley "," Brian Totty "]}
]}
Then splice a javascript statement to localhost for processing. Of course, test.com does not know the name of the method to be spliced, you need to specify the parameter "callback" in the url when the localhost sends the request. Let's see how localhost sends the request.
Localhost/books. php
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> Books </title>
<? Php include ('/components/headerinclude. php');?> </Head>
<Style type = "text/css">
. Book-title
{
Font-size: 15px;
Font-weight: bold;
Margin-top: 6px;
}
. Book-info
{
Color: # ccc;
Font-style: italic;
Border-bottom: dashed 1px # ccc;
}
</Style>
</Head>
<Body>
<Div style = "margin: 20px;">
<Div style = "font-size: 16px; font-weight: bold;"> Books </div>
<Div id = "books">
</Div>
</Div>
</Body>
</Html>
We want to display all the books in the div whose id is books. First, add a javascript function to display the book, that is, the callback function after obtaining the data, this can be written in this way in combination with the json format spliced above.
Copy codeThe Code is as follows:
Function displayBooks (books ){
Var books = books. book;
Var booksContainer = document. getElementById ('books ');
For (var I = 0; I <books. length; I ++ ){
Var tmp = Array ();
Tmp. push ('<div class = "book-title">' + books [I] ['@ bubutes']. name + '</div> ');
Tmp. push ('<div class = "book-info"> ');
Tmp. push ('<div> Publisher:' + books [I] ['@ attributes']. publisher + '</div> ');
Tmp. push ('<div> Author (s ):');
If (typeof books [I]. author = 'string '){
Tmp. push (books [I]. author );
} Else {
Var authors = books [I]. author;
For (var j = 0; j <authors. length; j ++ ){
Tmp. push (authors [j] + 'authorization '');
}
}
Tmp. push ('</div>'); // end of author
Tmp. push ('</div>'); // end of book info
BooksContainer. innerHTML + = tmp. join ('');
}
}
Then there is the key jsonp request method.
Copy codeThe Code is as follows:
Function getBooks (){
Var script = document. createElement ('script ');
Script. setAttribute ('type', 'text/javascript ');
Script. setAttribute ('src', 'HTTP: // test.com/bookservice.php? Callback = displayBooks ');
Document. body. appendChild (script );
}
GetBooks ();
In the getbooks () method, a script tag is dynamically created, and src is set to the service interface for getting data provided by test.com and the callback function is passed in. In this way, we can look at the page response, you can see this request in the Chrome Console
We can get the books of test.com under localhost.
Jquery implementation
Jsonp is also encapsulated in jquery, but jquery puts it into ajax and does not understand why. After all, this is not the same as ajax. Write a jQuery version
Copy codeThe Code is as follows:
Function getBooks (){
$. Ajax ({
Type: 'get ',
Url: 'http: // test.com/bookservice.php ',
DataType: 'jsonp ',
Jsonp: 'callback ',
JsonpCallback: 'displaybooks'
});
}
It looks exactly the same, but it is much more convenient. You don't need to create the script tag, but specify the ype as jsonp. The callback function is not placed in the url, but specified by two parameters respectively.
Security issues
Of course, using jsonp will cause security issues to some extent. If the requested site is not a new site, some malicious code may be included in the returned method call. Therefore, try to send requests to trusted sites. In addition, xss often uses jsonp to inject malicious code into the site.