Discuss the difference between JSON and JSONP and the use of jQuery ajax JSONP

  • 2020-03-30 04:20:20
  • OfStack

JSON and JSON
 
JSON (JavaScript Object Notation) is a lightweight data interchange format for exchanging information between browsers and servers.
 
JSONP(JSON With Padding) is JSON wrapped in a function call (or wrapped JSON).
 
JSON is a data format and JSONP is a data invocation.
 


 //JSON
 {
  " name " : " sb "
 }


 //JSONP
 callback({
  " name " : " sb "
 })

For security reasons, scripts (AJAX) cannot access content that is not in this domain. However, static resources are not limited by the domain policy, and static resources such as scripts, styles, pictures, etc. of any domain can be loaded. JSOP USES this principle to achieve cross-domain data acquisition.
 
Case 1:


 //Define the shoPrice function
 function showPrice(data) {
     alert("Symbol: " + data.symbol + ", Price: " + data.price);
 }


 //Contains the showPrice function and the parameter
in the Web page  <script type="text/javascript">
 function showPrice(data) {
     alert("Symbol: " + data.symbol + ", Price: " + data.price);
 }
 </script>
 <script type="text/javascript">showPrice({symbol: 'IBM', price: 91.42});</script>

This example shows how to call JavaScript functions with static JSON data as arguments.
 
  Example 2:
 
The first type of function call can be written in a js file on the server, loaded into the page with a script tag, and the tag can be created dynamically.
 


 <script type="text/javascript">
 // This is our function to be called with JSON data
 function showPrice(data) {
     alert("Symbol: " + data.symbol + ", Price: " + data.price);
 }
 
 var url = " remote.js " ; //The URL of the external script is
 //Dynamic insert script
 var script = document.createElement('script');
 script.setAttribute('src', url);
 
 //Load the script < br / >  document.getElementsByTagName('head')[0].appendChild(script);
 </script>

Code snippet of JSONP service implemented in PHP at the back end:
 


 $jsonData = getDataAsJson($_GET['symbol']);
 echo $_GET['callback'] . '(' . $jsonData . ');';
 //Print: showPrice ({" symbol ":" IBM ", "price" : "91.42"}); < br / >

This fits nicely with the definition of JSONP, which packages JSON data in function calls.
 
The above examples are from:
 
Using JSONP for cross-domain communication, part 1: combining JSONP with jQuery to quickly build powerful mashups
 
Use JSONP in jQuery
 
Don't be fooled by the way AJAX and JSONP are called in jQuery. They are very different in nature. AJAX is fetching non-page content through the XMLHttpRequest object, while JSONP is dynamic addition. Script> Tag to invoke the server script. While jQuery encapsulates JSONP as a form of AJAX, JSONP is not a form or a special case of AJAX.
 

 $.ajax({
     url: "http://query.yahooapis.com/v1/public/yql",
     jsonpCallback: "showPrice",
     jsonp: "callback",
     // tell jQuery we're expecting JSONP
     dataType: "jsonp",
     data: {
         q: "select title,abstract,url from search.news where query="cat"",
         format: "json"
     },
     // work with the response
     success: function( data ) {
         console.log( data ); // server response
     }
 });

Ajax request parameters:

DataType  The String

The type of data expected to be returned by the server. If not specified, jQuery automatically makes intelligent judgments based on the HTTP package MIME information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object and the script executes the script. The data returned from the server side is then parsed against this value and passed to the callback function. Available value:

"XML ": returns an XML document that can be processed with jQuery.

"HTML ": returns plain HTML information; The included script tags are executed when the dom is inserted.

"Script ": returns plain JavaScript code. The results are not automatically cached. Unless the "cache" parameter is set. Note: when a remote request is made (not under the same field), all POST requests become GET requests. (because it will be loaded using the script tags of the DOM)

"Json ": returns json data.

"Jsonp ": jsonp format. When calling a function in JSONP form, such as "myurl? The callback = & # 63;" JQuery will automatically replace ? Is the correct function name to execute the callback function.

"Text ": returns a plain text string
 
The json.
 
Overrides the name of the callback function in the jsonp request. Instead of "callback=?" The "callback" part of this GET or POST request URL parameter, such as {jsonp:'onJsonPLoad'}, causes the "onJsonPLoad" to be passed to the server.
 
JsonpCallback,
 
Specify a callback function name for jsonp. This value will be used to replace the random function name generated automatically by jQuery. This is primarily used to make jQuery generate unique function names, which make it easier to manage requests and provide easy callbacks and error handling. You can also specify the name of this callback function when you want the browser to cache GET requests. However, in practice, it is not necessary to write the callback function, such as showPrice in this case. If you do not write the callback function, you will not report an error, because jQuery automatically generates the callback function and takes the data out to the common success method call when dealing with JSONP. It might look like this:


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

That's the end of this article. Do you have a detailed understanding of jsonp? Any questions also please give me a message, we discuss together.


Related articles: