Home >Web Front-end >JS Tutorial >jsonp principle and use_javascript skills

jsonp principle and use_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:18:341069browse

First introduction to jsonp
The full name of jsonp is JSON with Padding, which is a solution created to solve cross-domain resource requests. Many times we need to obtain server data on the client side for operation. Generally, we will use ajax webservice to do this. However, if the data we want to obtain is not in the same domain as the current page, the famous same-origin policy (client-side scripts in different domains) Without explicit authorization, the other party's resources cannot be read or written) and the request will be rejected for security reasons, that is, we cannot directly send requests to other domains to obtain resources.
There is a books.php on the localhot domain, which contains a script that sends a get request to books.php in the test.com domain, hoping to obtain its book list resource. This is a cross-domain request resource

Copy code The code is as follows:

$.ajax({
type:'get',
url: 'http://test.com/books.php'
});

The page will report an error like this: XMLHttpRequest cannot load http://test.com/books.php . Origin http://localhost is not allowed by Access-Control-Allow-Origin.jsonp appeared to solve this problem.

jsonp principle
Although there are restrictions on the same origin policy, not all resources on HTML must be in the same domain. In order to save traffic or load faster, our common pages use Google or Microsoft's jQuery CDN, we can quote jQuery by writing this on the page

Copy the code The code is as follows:



The src attribute of iframe, img, style, script and other elements can directly request resources from different domains. jsonp officially uses the script tag to request resources across domains

Simple implementation
books.php of localhost hopes to obtain the books list of domain test.com. The book list in domain test.com is stored in books.xml
test.com/ books.xml

Copy code The code is as follows:




David Flanagan                                                                                                                 author>Laura Thomson


books.xml, there needs to be a mechanism in test.com to convert xml into json (this is why it is called jsonp, in fact, like ajax, the returned data is not necessarily in json format, but json is easy to use), and dynamically spliced A javascript call statement is returned. In this example, the php page is directly used to splice
test.com/bookservice.php




Copy code

The code is as follows:

$path=$_SERVER["DOCUMENT_ROOT"].'/books.xml'; $json=json_encode(simplexml_load_file($path) ); $callbackFn=$_GET['callback']; echo "$callbackFn($json);";?>

In this way, first convert the xml file content into a json object


Copy code

The 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 it is spliced ​​into a javascript statement and handed over to localhost for processing. Of course, test.com does not know the name of the method that should be spliced What, localhost needs to pass a parameter called callback (this is optional, just synchronize both sides) in the URL when sending the request. Let’s see how localhost sends a request
localhost/books.php
Copy the code The code is as follows:




Books

                                                                                                                                                                                                                                                                                  font-weight:bold;
margin-top:6px;
}

.book-info
}
 



  
Books

                                                                              body>



We want to display all books in the div with the id of books. First, add a javascript function to display the book, that is, after obtaining the data The callback function, combined with the json format spliced ​​above, can be written as follows




Copy the code


The code is as follows:


function displayBooks(books){
            var books=books.book;
            var booksContainer=document.getElementById('books');
            for(var i=0;i                var tmp=Array();
                tmp.push('
' books[i]['@attributes'].name '
');
                tmp.push('
');
                tmp.push('
Publisher: ' books[i]['@attributes'].publisher '
');
                tmp.push('
Author(s): ');
                if(typeof books[i].author=='string'){
                    tmp.push(books[i].author);
                }else{
                    var authors=books[i].author;
                    for(var j=0;j                        tmp.push(authors[j] ' ');
                    }
                }
                tmp.push('
'); //end of author
                tmp.push('
'); //end of book info
                booksContainer.innerHTML =tmp.join('');
            }
        }

然后是关键的jsonp请求的方法了
复制代码 代码如下:

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();


在getbooks()方法中动态创建了一个script标签,设置其src为test.com提供的获取数据的service接口并传入回调函数,这样我们可以看看页面的反应,在Chrome控制台下可以看到这条请求
jsonp principle and use_javascript skills

我们就可以在localhost下获取test.com的books了
jsonp principle and use_javascript skills

jquery实现
在jquery中也有对jsonp的封装,不过jquery把其放到了ajax中,不明白为什么,毕竟这东西和ajax不太一样。写一个jQuery版的
复制代码 代码如下:

function getBooks(){
$.ajax({
type:'get',
url:'http://test.com/bookservice.php',
dataType:'jsonp',
             jsonp:'callback',
                       jsonpCallback:'displayBooks'
                                                 🎜>Looks exactly the same, but more convenient There is no need to create a script tag yourself. Specify the dataType as jsonp. The callback function is no longer placed in the url, but is specified using two parameters.

Security Issues
Of course, using jsonp will cause security issues to a certain extent. If the requested site is not a newcomer's site, some malicious code may be included in the returned method call. So try to send requests to trusted sites. In addition, xss often uses jsonp to inject malicious code into the site.

Statement:
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