VUE--the birth, principle and application examples of JSONP

Source: Internet
Author: User

Questions:

There is a button on the page that will update the contents of a box in the page.

Ajax can easily satisfy the need for data transformation without having to refresh the entire page.

However, one drawback of Ajax is that he does not allow cross-domain requests for resources.

If my code is on Codepen, I can't put my data on the Codepen website, then I can only put it on my own server, so I can't access this data through Ajax.

Solve:

To implement this cross-domain resource request, there are a number of workarounds that list some of the following:

    1. Let the server load the remote data and then provide it to the browser when the user requests it.
    2. Load foreign files with <script> or <iframe> tags. (because their SRC attribute allows access to resources anywhere.) )
    3. The Cross-origin Resource sharing (CORS, cross-domain resource sharing) developed by the consortium.
    4. JSONP

the birth and principle of Jsonp:

JSONP's principle is exactly the same as the second solution, except that he is more convenient, and the cross-domain communication is given a name of "JSONP".

So the first thing to understand is how the second approach works:

Principle: If a page is loaded with a foreign JS file, the browser will automatically execute the code in this file.

So if localhost wants to use a JSON data above jsonhost, localhost can get jsonhost to do it for him, Jsonhost provide him with a JS file and pass in the required data to the function to be called. The result is exactly the same as the effect of localhost calling the function itself.

Jsonhost:

<script type= "Text/javascript" >
var json= ' ["customername1", "customername2"] ';
Callbackfunction (JSON);
</script>

localhost

<script type= "Text/javascript" >
var json= ' ["customername1", "customername2"] ';
callbackfunction (JSON);
</script>
<script type= "Text/javascript" > function callbackfunction(Result) { var html = ' <ul > '; for (var i = 0; i < result.length; i++) { html + = ' <li> ' + result[i] + ' </li> '; } HTML + = ' </ul> '; document.getElementById (' Divcustomers '). InnerHTML = html; } </script>

In this way, localhost can already use the data in Jsonhost.

Then localhost said, "I want to be able to execute the callbackfunction (JSON) again when my user taps a button, not after the page is loaded."

So he needs to create <script> tag dynamically:

function Callbackfunction (Result) {    var html = ' <ul> ';    for (var i = 0; i < result.length; i++)    {        html + = ' <li> ' + result[i] + ' </li> ';    }    HTML + = ' </ul> ';    document.getElementById (' Divcustomers '). InnerHTML = html;} $ (". Btn"). Click (function () {    var script = document.createelement (' script ');    Script.setattribute (' src ', ' http://jsonhost/json.js ');    document.getElementsByTagName (' header ') [0].appendchild (script);});

When this is done, the effect is the same as an AJAX asynchronous request.

Here, the story seems to end like this, but suddenly one day, another otherhost ran and Jsonhost said, he wants to deal with Json,jsonhost through jsoncallbackfunction difficult, so they get together, To find a way, you can get the same data without having to use the same function name all.

Eventually they came up with a perfect solution.--jsonhost uses a variable instead of a function name, and when localhost and otherhost request data, the name of the variable is passed in, so that each function name can be determined separately.

Jsonhost:

<?php header (' Content-type:application/json '); Tells the object receiving the data that this page output is JSON data $json = ' [' customername1 ', ' customername2 '] '; Echo $_get[' callback ']. "(" .  

localhost

<script type= "Text/javascript" >    function Getjson (url,funname) {        var script = document.createelement (' Script ');        Script.setattribute (' src ', url+funname);        document.getElementsByTagName (' head ') [0].appendchild (script);    }    function callbackfunction(Result)    {        var html = ' <ul> ';        for (var i = 0; i < result.length; i++)        {            html + = ' <li> ' + result[i] + ' </li> ';        }        HTML + = ' </ul> ';        document.getElementById (' Divcustomers '). InnerHTML = html;    }    $ (". Btn"). Click (function () {        Getjson ("http://jsonhost/jsonp.php?jsoncallback=", "callbackfunction ");    }); </script>

Otherhost:

<script type= "Text/javascript" >    function Getjson (url,funname) {        var script = document.createelement (' Script ');        Script.setattribute (' src ', url+funname);        document.getElementsByTagName (' head ') [0].appendchild (script);    }    function jsoncallbackfunction(Result)    {        console.log (result);    }    $ (". Btn"). Click (function () {        Getjson ("http://jsonhost/jsonp.php?jsoncallback=", "jsoncallbackfunction ");    }); </script>

In this way, the use of what function name is different from the host's own things, they do not interfere with each other, jsonhost do not worry about this matter, concentrate on providing the data can be. Other hosts have come to get JSON. So this pattern is widely used, and then this communication is named "JSONP".

If you use jquery, you don't have to name the function and pass it to the parameter, because the function name is not important, he is just a code name, jquery will help us to automatically generate a function, and then the resulting data to the function. jquery also helps us create script tags, and we just need to be concerned with how to handle this data.

<script src= "Http://apps.bdimg.com/libs/jquery/1.8.3/jquery.js" ></script><script>    $. Getjson ("http://jsonhost/jsonp.php?jsoncallback=", function (data) {            var html = ' <ul> ';            for (var i = 0; i < data.length; i++)            {                    html + = ' <li> ' + data[i] + ' </li> ';            }            HTML + = ' </ul> ';                       $ (' #divCustomers '). HTML (HTML);    }); </script>
jquery encapsulates Jsonp into Ajax, but in essence the two technologies are completely different. The JSONP principle is that the current Web page dynamically executes an exotic return of the JS code, which is a function that executes the request data. The browser executes this function, and the effect is the same as the current field to get the data execution function.

Application Examples:

After knowing the principle, I can't wait to use JSONP to get the data. This is implemented in PHP.

first, there needs to be a server, if there is no server, you can use the Wampserver software simulation of one, the software will also establish an integrated environment, you can run PHP files. Click to view wampserver Tutorial

With your own server and PHP running environment, you can start. You want to get local data on the Codepen.

Native PHP:

 <?php Header (' Content-type:application/json ');//Tell the object receiving data this page output is JSON data $quotes = ' [{"quote": "If you can\    ' t get rid of the skeleton in your closet, you\ ' d best teach it to dance. "Author": "George Bernard Shaw"},  {"Quote": "We\ ' ll always has Paris.", "Author": "Casablanca"}, {"quote": "A mathematician is a device for turning coffee to theorems. "," Author ":" Paul Erdos "}, {" quote ":" Do, or does not. " There is no \ ' try\ ', "Author": "Star Wars:empire Strikes Back"}, {"quote": "Some cause happiness wherever they go; Others, whenever they go. "," Author ":" Oscar Wilde "}, {" quote ":" Problems worthy of attack prove the IR worth by fighting back. "," Author ":" Paul Erdos "}, {" quote ":" Maybe the-world is another planet\ ' s Hell. "," Author ":" Aldous Huxley "}] '; Echo $_get[' callback '].  "(" . $quotes. ")";? > 

JS on the Codepen:

function Update () {    var index=math.floor (Math.random () *11);    $.getjson ("http://localhost/quotes.php?callback=", function (data) {        var num=math.floor (Math.random () *6);        $ (". Wrap"). FadeOut (600,function () {            $ (". Quo"). HTML (data[num].quote);            $ (". Auth"). html (data[num].author);            $ ("Body,. Quote-box button"). CSS ("Background-color", Colors[index]);            $ (". Wrap"). CSS ("Color", Colors[index]);        }). FadeIn ();    }); $ (document). Ready (function () {    update ();    $ (". Update"). Click (update);});

Click to view the online demo, you must impersonate the server and create a PHP environment and add PHP files to run.

And be careful to change the Codepen HTTPS to HTTP.

After success, you can see that the sent request, passed to callback, is a jquery auto-generated function:

The return is also the function call data:

If you do not want to configure, you can apply the API provided by other websites, the implementation principle is the same. Demo

Reference:

    • JSONP Tutorials
    • "Basic jquery Tutorial"
    • Talk about JSON and JSONP, maybe you'll be enlightened, with jquery use cases

VUE--the birth, principle and application examples 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.