A brief analysis of the difference between JSON and JSONP and the conversion of the format after obtaining the JSON data via AJAX _ajax related

Source: Internet
Author: User
Tags data structures

The difference between JSON and JSONP (JSON is the purpose, JSONP just means) is described as follows:

Word, JSON returns a string of data; Jsonp returns the script code (contains a function call);

JSON is actually an object in JavaScript that is exactly the same as the Var obj={}, but it can be infinitely extensible in quantity. Simply put, JSON is actually a JavaScript object (object) and Array (Array, in fact, also objects) where the good friends are, you embed me. I embed you in a nested n multilayer to simulate many complex data structures.

JSON is easy to read and write, but also easy to machine parsing and generation, relatively high transmission rate of the network, functional sites often have a large number of exchange data, and JSON by virtue of its strong expressiveness and high color value gradually become the ideal front and back end data exchange language. The XML predecessors, I think should be like Microsoft's XP to retire.

Homologous (do not know homologous strategy of children's shoes please own Baidu) Data interchange format of the front and back to determine the use of JSON, then the question is, if I want to get someone else on the site to provide data swollen do it? That is, cross-domain read data problem (do not drill horn said you do not need to read other Web site data, believe me, you have to do sooner or later), JSON can not do? The answer is no Way, why, because JSON is just plain text format, so that you can easily get the server without any security and confidentiality, so that the internet world is not a mess, the problem of those cattle X's specifications have been thought of, so the use of homologous policy to restrict file acquisition. The final result is only like the IMG, script, iframe can specify the SRC attribute of the label has Cross-domain access to other people's Web site data (pictures, scripts, source files are actually data) ability. Like what:

<!--Jing Dong-->

<!--Baidu Cdn-->

It seems that direct access to JSON does not work, so is there any other way to get the data? So Jsonp was discovered by intelligent developers, and why it was discovered, not invented, because it didn't involve any new technology, just like discovering Ajax.

Jsonp principle is this, website a needs to get the data of the website B, the website b says I give you a method, "1." You use the <script src= "http://www.B.com/open.js" ></script> tag to get the Open.js file (responsibility for Site B), which has the data you need. 2. The method name for processing data after you have obtained the data (always processing the data) must be named Foo (the responsibility and obligation of the data requester) ", which is equivalent to establishing an agreement between the B Web site and the requesting data provider, requiring the requester to follow the rules, If the requester cannot comply with the above two at the same time, the data cannot be obtained as expected. Well, that's equivalent to setting up a latent rule.

Open.js Content

Foo ({"name": "B", "Age": 23}); Why not write directly to the JSON data {"name": "B", "Age": 23}, the reason is very simple, in the JS file must conform to the JS Grammar bar
//This is why the Protocol clearly stipulates that the process of processing the data is named Foo, Because the B Web site is to return the data in the assumption that the requester's script has defined the data processing method foo;
//or else it will be reported as Foo is not defined error

Site a script must have

function foo (data) {
console.log (data);
Todo.. 

Ah! Although I turned a corner, but the data finally got, website A, site B are very happy, then the problem comes, the Site C said also need to get the site B data, site B to give it to the agreement, the Site C take over a look, grass mud horse ah, foo this name has been in their own script file 6868 lines used, and has been used in various corners of the script, the bulk of the replacement will lead to many potential bugs Ah, site B was nasty decided to change Foo to fool, site A immediately jumped up, because their site has been used in many places with Foo reference data.

To avoid this, the cattle x coax developers use the dynamic generation of JS file method, PHP version is as follows:

open.php

<?php
Header (' Content-type:application/javascript ');
$jsonCallback = Htmlspecialchars ($_request [' Callback ']); Gets the requestor's custom callback function name
$jsonData = ' {' name ': ' B ', ' age ': 23} ';//The JSON data to be returned
Echo $jsonCallback. "(" . $jsonData. ")"; Output JSONP format data, that is, a line of function call statements
?> 

Well, as to why PHP can return to the JS format file, Baidu.

So site A uses the <script src= "Http://www.B.com/open.php?callback=foo" ></script> to request data, does not need to modify any variables, returned to a script file content is:

Foo ({"name": "B", "Age": 23}); The so-called JSONP, is a function call, the data are passed to the parameters of the package, do not wear a vest do not know the 
Site C with <script src= "http://www." B.com/open.php?callback=blah "></script> to request data, the contents of the script file returned to C are:
blah ({" Name ":" B "," Age ":}); 
Site N on the <script src= "http://www. B.com/open.php?callback=what "></script> to request data, the contents of the script file returned to N are:

Problem solved, everyone took the desired data and avoided naming conflicts.

JSONP full name is called JSON with padding, very image, is the JSON object in accordance with the form of JS syntax to make other sites can request, that is, the JSON data encapsulated into JS files;

JSON is the ideal data interchange format, but there is no way to get directly across the domain, so the JSON package (padding) in a legitimate JS statement as a JS file passed. That's the difference between JSON and JSONP, JSON is what you want, and JSONP is a common way to do that, and of course, the last thing you get and deal with is JSON. So JSON is the purpose, jsonp just means. JSON is always used, and JSONP can only be used if you are getting data across domains.

Understand the difference between JSON and JSONP, in fact, the Cross-domain access to data in Ajax is very well understood and realized, the same time and nothing special, direct access on the line, cross-domain time need to turn a bend to achieve the goal.

Enclose the AJAX request JSON data instance in jquery:

(homologous):

$.ajax ({
URL: "Persons.json",
success:function (data) {
console.log (data);
ToDo..
}

(Cross-domain):

$.ajax ({
URL: "http://www. B.com/open.php?callback=? ",
dataType:" Jsonp ",
success:function (data) {
console.log (data);
ToDo..
}

jquery has jsonp encapsulated into Ajax, very reasonable, because after all, most of the JSONP request is Ajax, the Ajax specific use of jquery please own Baidu, the other thing to note is that different websites provide the data interface of the $_request [' Callback '] is not necessarily callback is also likely to be CB,CBK, etc., you must read the service side of the use of the interface to provide detailed documentation.

The following is a description of the conversion of the format of the JSON data from "Night Young 0906" written by Ajax

In some cases, the JSON data obtained may be of type string and need to be formatted as a JSON object for easy parsing.

A the JSON acquired by native JS via Ajax

The data returned at this time by default is string, so you need to convert it to a JSON object using the eval () function. You need to be aware of the format of strings within functions: eval ("(" + data+ ")"), because the returned string is inside {}, Eval will recognize the brace as the beginning and end of the JS code block, so you must add () and force it into an object to process.

b) jquery Access

1: The JSON object is returned by using Ajax () to asynchronously request and setting the type to JSON.

2: By Using $.getjson (Url,data1,function (DATA2,STATUS,XHR) {//...}) equivalent to Ajax () Method gets a JSON object as well. Where Data1 is the data that is sent along with the request, data2 the data that is returned by the server, the JSON object.

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.