JSONP principle and usage in jQuery, jsonp principle jquery

Source: Internet
Author: User

JSONP principle and usage in jQuery, jsonp principle jquery

JSONP Principle

JSON and jsonp json (JavaScript Object Notation) are lightweight data exchange formats used to exchange information between browsers and servers. JSONP (JSON With Padding) is the JSON (or wrapped JSON) packaged in the function call ). JSON is a data format, and JSONP is a data call method. Copy code 1 // JSON2 3 {4 5 "name": "sb" 6 7} copy code 1 // JSONP2 3 callback ({4 5 "name ": "sb" 6 7}) Copying code for security reasons, the script (AJAX) cannot access non-local content. However, static resources are not restricted by domain policies and can load scripts, styles, images, and other static resources in any domain. JSOP uses this principle to obtain data across domains. Example 1: 1 // define the shoPrice function 2 function showPrice (data) {3 alert ("Symbol:" + data. symbol + ", Price:" + data. price); 4} copy code 1 // include the showPrice function and parameter 2 <script type = "text/javascript"> 3 function showPrice (data) on the Web page) {4 alert ("Symbol:" + data. symbol + ", Price:" + data. price); 5} 6 </script> 7 <script type = "text/javascript"> showPrice ({symbol: 'ibm ', price: 91.42 }); </script> copy the Code. This example shows how to call a JavaScript letter using static JSON data as a parameter. Number. Example 2: the first function call can be written in a js file and placed on the server, loaded to the page with the script tag, and the tag can be dynamically created. Copy code 1 <script type = "text/javascript"> 2 // This is our function to be called with JSON data 3 function showPrice (data) {4 alert ("Symbol: "+ data. symbol + ", Price:" + data. price); 5} 6 7 var url = "remote. js "; // external script URL 8 // dynamic insert script 9 var script = document. createElement ('script'); 10 script. setAttribute ('src', url); 11 12 // load script13 document. getElementsByTagName ('head') [0]. appendChild (scrip T); 14 </script> copy the code remote. the js content is the same as the one previously written in the tag: 1 showPrice ({symbol: 'ibm ', price: 91.42}); the JavaScript code that is dynamically inserted, the JSON data to be passed is used as the parameter. The parameter of the showPrice function call statement. So the question is, will the showPrice function be called every time data is obtained? This requires the frontend and backend programmers to make a good deal of agreement. Of course, this is a lot of inconvenience, especially for open interfaces for public development. JSOP: a callback function name parameter can be passed at the front end. The backend receives the callback function name parameter, generates a call to the function, and transmits JSON data as a parameter, when you arrive at the client, insert it into the page and start execution. Example 3: dynamically insert code with the callback parameter: copy code 1 <script type = "text/javascript"> 2 // This is our function to be called with JSON data 3 function showPrice (data) {4 alert ("Symbol: "+ data. symbol + ", Price:" + data. price); 5} 6 7 var url = "remote. js? Callback = 'showprice' "; // URL of the external script 8 9 // dynamic insert script 10 var script = document. createElement ('script'); 11 script. setAttribute ('src', url); 12 13 // load script14 document. getElementsByTagName ('head') [0]. appendChild (script); 15 </script> copy the code snippet of the JSONP service implemented by PHP on the Code backend: 1 $ jsonData = getDataAsJson ($ _ GET ['symbol']); 2 echo $ _ GET ['callback']. '('. $ jsonData. ');'; 3 // print: showPrice ({"symbol": "IBM", "price": "91.4" 2 "}). It fits well with the JSONP definition and is packaged in JSON data in function calls. The preceding examples are from: Use JSONP for cross-origin communication. Part 1: Use JSONP and jQuery to quickly build powerful mashups. In jQuery, the call methods of jsonp ajax and JSONP in jQuery seem very similar, never be confused by such phenomena. They are essentially quite different. AJAX uses the XMLHttpRequest object to obtain non-page content, while JSONP dynamically adds the <script> tag to call the server script. Although jQuery encapsulates JSONP as a form of AJAX, JSONP is not a form or special case of AJAX. Copy code 1 2 $. ajax ({3 url :" http://query.yahooapis.com/v1/public/yql ", 4 5 jsonpCallback:" showPrice ", 6 jsonp:" callback ", 7 8 // tell jQuery we're re expecting JSONP 9 dataType:" jsonp ", 10 11 12 data: {13 q: "select title, abstract, url from search. news where query = \ "cat \" ", 14 format:" json "15}, 16 17 // work with the response18 success: function (data) {19 console. log (data); // server response20} 21}); copy the code parameter explanation: jsonp, override the name of the callback function in the jsonp request. To the Russian value to replace "callback = ?" In this GET or POST request, the "callback" part of the URL parameter, for example, {jsonp: 'onjsonpload'} causes "onJsonPLoad" to be passed to the server. JsonpCallback: Specifies a callback function name for jsonp. This value is used to replace the random function name automatically generated by jQuery. This function is mainly used to make jQuery generate a unique function name, which makes it easier to manage requests and conveniently provide callback functions and error handling. You can also specify the callback function name when you want the browser to cache the GET request. However, in actual use, the callback function is not used, for example, showPrice in this example. If this parameter is not set, no error is returned because when jQuery is processing JSONP, the callback function is automatically generated for you and the success method is called to obtain the data. Function success_jsonpCallback (data) {success (data );}

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.