First knowledge of JSONP

Source: Internet
Author: User
Tags script tag jquery cdn

The JSONP full name is the JSON with Padding, which is the solution for resolving cross-domain request resources. Most of the time we need to get the server data on the client, generally we will use Ajax+webservice to do this, but if we want to get the data and the current page is not a domain, the well-known homologous policy (client script in different domains without explicit authorization, Cannot read and write to each other's resources) will be rejected for security reasons, that is, we cannot send requests directly to other domains to obtain resources.

There is a books.php on the Localhot domain that contains a script that sends a GET request to the test.com domain books.php and wants to get its book list resource, which is a cross-domain request resource

$.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 to solve this problem.

JSONP principle

Although there are same-origin policy restrictions, but not all the resources on the HTML must be the same domain, our common page in order to save traffic or load speed using Google or Microsoft JQuery CDN, on the page we can write this can reference jquery

<script  type= "Text/javascript"    src= "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>

The src attribute of the IFRAME, IMG, style, script, and other elements can request resources directly from different domains, JSONP formally using the script tag to request resources across domains

Simple implementation

Books.php of LocalHost wants to get a books list of domain test.com, stored in books.xml in the domain test.com book list

Test.com/books.xml

<?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 can not directly get books.xml, in test.com need a mechanism to convert XML into JSON (this is why called JSONP, in fact, like Ajax, the returned data is not necessarily JSON format, but JSON is very useful), and dynamically splicing a JAVASC Ript Call statement returned, this example directly using the PHP page stitching

test.com/bookservice.php

<?php    $path =$_server["Document_root"]. ' /books.xml ';    $json =json_encode (Simplexml_load_file ($path));    $callbackFn =$_get[' callback '];    echo "$callbackFn ($json); >

This first converts the contents of the XML file into a JSON object

{"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"]}]}

And then stitching it up for a JavaScript statement and handing it over to localhost, Of course, test.com do not know what the method should be splicing called, need to localhost in the URL when sending a request to a call callback (this also casually, both sides synchronous on the line) parameters indicated. See how localhost sends the request.

localhost/books.php

<! DOCTYPE html>

We want to show all the book in the Div with the ID books, first to add a JavaScript function to display the book, that is, the callback function after the data, and the JSON format with the above stitching can be written

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][' @attributes '].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]+ ' &emsp; '); }} tmp.push (' </div> '); End of author Tmp.push (' </div> '); End of book Info Bookscontainer.innerhtml+=tmP.join ("); }        }

And then it's the key Jsonp request method.

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 was created dynamically, set its src to test.com the service interface to fetch the data, and pass in the callback function, so we can look at the response of the page and see the request under the Chrome console.

So we can get test.com's books under localhost.

jquery implementation

There's also a package for JSONP in jquery, but jquery puts it in Ajax and doesn't understand why, after all, it's not the same thing as Ajax. Write a jquery version of the

function Getbooks () {            $.ajax ({                type: ' Get ',                URL: ' http://test.com/bookservice.php ',                dataType: ' Jsonp ',                jsonp: ' Callback ',                jsonpcallback: ' Displaybooks '            });        }

Looks exactly the same, but a lot of convenience, do not have to create a script tag God horse, indicating that datatype is JSONP, the callback function is not placed in the URL, but the use of two parameters are indicated separately.

Security issues

Of course, the use of JSONP will cause a certain degree of security problems, if the requested site is not a trusted site, then the returned method calls may contain some malicious code. So try to send a request to a trusted site. In addition, XSS often uses JSONP to inject malicious code into the site.

First knowledge of JSONP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.