JSONP principle and the use of jquery

Source: Internet
Author: User

Jsonp principle

JSON and JSONP

JSON(JavaScript Object Notation) is a lightweight data interchange format for exchanging information between a browser and a server.

JSONP (JSON with Padding) is the json (or JSON of the package)thatis packaged in a function call .

 JSON is a data format, and JSONP is a way to call data.

1 // JSON 2 3 {45"name": "SB"67 }
1 // JSONP 2 3 callback ({45"name": "SB"67 })

For security reasons, scripting (AJAX) cannot access content that is not part of the domain. However, static resources are not restricted by the domain policy, can load arbitrary domain scripts, styles, pictures and other static resources, JSOP is to use this principle to achieve cross-domain data acquisition.

Example 1:

1 // defining the Shoprice function 2 function Showprice (data) {3     alert ("Symbol:" + Data.symbol + ", Price:" + data.price); 4 }
1 //include showprice functions and parameters in Web pages2 <Scripttype= "Text/javascript">3 functionShowprice (data) {4 Alert ("Symbol:" +Data.symbol+ ", Price:" +data.price);5 }6 </Script>7 <Scripttype= "Text/javascript">Showprice ({symbol:'IBM', Price:91.42});</Script>

This example shows how to call a JavaScript function with static JSON data as a parameter.

Example 2:

The first function call can be completely written in a JS file on the server, loaded into the page with a script tag, and this tag can be created dynamically.

1 <Scripttype= "Text/javascript">2 //We function to being called with JSON data3 functionShowprice (data) {4 Alert ("Symbol:" +Data.symbol+ ", Price:" +data.price);5 }6 7 varURL="Remote.js";//the URL of the external script8 //Dynamic Insert Script9 varScript=Document.createelement ('Script');Ten Script.setattribute ('src', URL); One  A //Load Script - document.getElementsByTagName ('Head')[0].appendchild (script);  - </Script>

The contents of Remote.js are the same as those previously written in the label:

1 showprice ({symbol: ' IBM ', price:91.42});

Dynamically inserted JavaScript code, the JSON data to be passed as a parameter, showprice the arguments of the function call statement.

So the question comes, do you call the Showprice function every time you get the data? This requires the front-end program ape to make a pact, of course, this has a lot of inconvenience, especially for open interfaces to the public to develop the situation. Jsop this: Supports the front end passing a callback function name parameter, the backend receives the callback function name parameter, then generates a call to the function, passes the JSON data as a parameter, and inserts it into the page when the client arrives to execute.

Example 3:

Dynamic insert code with callback parameters:

1<script type= "Text/javascript" >2  //We function to being called with JSON data3  functionShowprice (data) {4Alert ("Symbol:" + Data.symbol + ", Price:" +data.price);5  }6   7 varurl = "remote.js?callback= ' Showprice '";//the URL of the external script8 9 //Dynamic Insert ScriptTen varScript = document.createelement (' script '); OneScript.setattribute (' src ', URL); A   - //Load Script -document.getElementsByTagName (' head ') [0].appendchild (script);  the</script>

Code snippet for the JSONP service implemented by the backend in PHP:

1 $jsonData = Getdataasjson ($_get[' symbol '); 2 Echo $_get[' callback '. ' ('. $jsonData. ‘);‘ ; 3 // Print: Showprice ({"symbol": "IBM", "Price": "91.42"});

This is a good fit for the definition of JSONP, which is packaged in JSON data in function calls.

Here are a few examples from:

Use JSONP for cross-domain communication, Part 1 : combining JSONP and jQuery /c8> quickly build a powerful mashup

Using Jsonp in jquery

Ajax and Jsonp in jquery seem to be very similar, do not be confused by this phenomenon, they are very different in nature. Ajax is to get non-page content through XMLHttpRequest objects, while JSONP is a dynamic add <script> tag to invoke server scripts. Although jquery encapsulates Jsonp as a form of Ajax, JSONP is not a form or a special case of Ajax.

1 2 $.ajax ({3URL: "HTTP://QUERY.YAHOOAPIS.COM/V1/PUBLIC/YQL",4  5Jsonpcallback: "Showprice",6JSONP: "Callback",7  8     //Tell JQuery we ' re expecting JSONP9DataType: "Jsonp",Ten   One      A data: { -Q: "Select Title,abstract,url from Search.news where query=\" cat\ "", -Format: "JSON" the     }, -   -     //Work with the response -Successfunction(data) { +Console.log (data);//Server Response -     } +});

Parameter explanation:

Jsonp

Overrides the name of the callback function in the JSONP request. To the callback= value to replace "the"? The "callback" part of this Get or POST request URL parameter, such as {jsonp: ' onjsonpload ', causes "onjsonpload" to be passed to the server.

Jsonpcallback,

Specifies a callback function name for JSONP. This value will be used instead of the random function name generated by jquery automatically. This is primarily used to create a unique function name for jquery, which makes it easier to manage requests and provides a convenient way to provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache a GET request. However, the actual use of the process, do not write callback functions, such as the showprice in this example, do not write or error, because jquery in the process of JSONP, automatically help you generate a callback function and take the data out to success method calls. It might look like this:

function success_jsonpcallback (data) {success (data);}

Other parameters can be queried on the jquery website: http://api.jquery.com/jquery.ajax/

Reference:

JS using JSONP, VAR implementation of the front-end cross-domain

Talk about JSON and JSONP, maybe you'll be enlightened, with jQuery Use cases

JSONP: What is the working principle?

Working with JSONP

Cross-domain request for jquery Ajax JSONP use

JSONP principle and the use of jquery

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.