On the difference between JSON and JSONP and the use of jquery Ajax Jsonp _jquery

Source: Internet
Author: User
Tags error handling script tag

JSON and JSONP

JSON (JavaScript Object notation) is a lightweight data interchange format for exchanging information between browsers and servers.

JSONP (JSON with Padding) is the JSON (or wrapped JSON) packaged in a function call.

JSON is a data format, and JSONP is a way of calling data.

Copy Code code as follows:

Json
{
"Name": "SB"
}

Copy Code code as follows:

JSONP
Callback ({
"Name": "SB"
})

Scripting (AJAX) cannot access content that is not part of the domain for security reasons. However, static resources are not restricted by domain policy and can load static resources, such as scripts, styles, pictures, and so on, in any domain, and jsop is the principle used to achieve cross-domain data acquisition.

Example 1:

Copy Code code as follows:

Defining Shoprice Functions
function Showprice (data) {
Alert ("Symbol:" + Data.symbol + ", Price:" + data.price);
}

Copy Code code as follows:

Include Showprice functions and parameters in a 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 a JavaScript function with static JSON data as a parameter.

Example 2:

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

Copy Code code as follows:

<script type= "Text/javascript" >
This is we function to being called with JSON data
function Showprice (data) {
Alert ("Symbol:" + Data.symbol + ", Price:" + data.price);
}

var url = "Remote.js"; URL of the external script
Dynamic Insert Script
var script = document.createelement (' script ');
Script.setattribute (' src ', url);

Load Script
document.getElementsByTagName (' head ') [0].appendchild (script);
</script>

Remote.js's content is the same as the one previously written in the label:

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

Dynamically inserted JavaScript code that will pass the JSON data as a parameter, showprice the arguments to the function call statement.

So the question is, do you call the Showprice function every time you get the data? This requires the back-end program ape to make a pact, of course, this has a lot of inconvenience, especially for open interface to the public development situation. Jsop This process: supports the front-end pass a callback function name parameter, the backend receives the callback function name parameter, then generates the call to the function, passes the JSON data as the parameter, when arrives the client inserts it to the page to begin execution.

Example 3:

Dynamic insert code with callback parameters:

Copy Code code as follows:

<script type= "Text/javascript" >
This is we function to being called with JSON data
function Showprice (data) {
Alert ("Symbol:" + Data.symbol + ", Price:" + data.price);
}
var url = "remote.js?callback= ' Showprice '"; URL of the external script
Dynamic Insert Script
var script = document.createelement (' script ');
Script.setattribute (' src ', url);
Load Script
document.getElementsByTagName (' head ') [0].appendchild (script);
</script>

Code snippet for JSONP services implemented in PHP by backend:

Copy Code code as follows:

$jsonData = Getdataasjson ($_get[' symbol '));
Echo $_get[' callback ']. ' ('. $jsonData. ');';
Printing: Showprice ({"symbol": "IBM", "Price": "91.42"});

Well, it fits the definition of JSONP, and packages the JSON data in a function call.

The above examples come from:

Cross-domain communication using JSONP, part 1th: Quickly build powerful mashups with JSONP and JQuery

using JSONP in jquery

Ajax and Jsonp in jquery look very much alike, do not be fooled by this phenomenon, they are fundamentally different. Ajax is the XMLHttpRequest object to get the non page content, and JSONP is dynamic add <script> tag to invoke server script. While jquery encapsulates Jsonp as a form of Ajax, JSONP is not a form or a special case of Ajax.

Copy Code code as follows:

$.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 Parameter Description:

DataType String

The type of data expected to be returned by the server. If not specified, JQuery will automatically intelligently judge against HTTP packet mime information, such as XML MIME types being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server side is then parsed against this value and passed to the callback function. Available values:

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

HTML: Returns plain text HTML information, and the included script tag executes when the DOM is inserted.

Script: Returns the plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. ' Note: ' At remote request (not in the same domain), all post requests will be converted to get requests. (because it will be loaded using the DOM's script tag)

"JSON": Returns JSON data.

"JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To the correct function name to execute the callback function.

' Text ': Returns a plain text string

Jsonp,

Overrides the name of the callback function in the JSONP request. To the Russian equivalent of the "callback=?" The "callback" section 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 to replace the random function name that jquery automatically generates. This is primarily used to allow jquery to generate unique function names, which makes it easier to manage requests and easily provides callback functions and error handling. You can also specify this callback function name when you want the browser to cache a GET request. However, in the actual use of the process, and do not write a callback function, such as the showprice in this example, do not write will not error, because jquery in processing Jsonp, automatically help you generate the callback function and the data out to a total of success method calls. Maybe like this:

Copy Code code as follows:

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

The above is the entire content of this article, whether we have a meticulous understanding of the JSONP. Have any question also please give me the message, everybody discusses together.

Related Article

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.