Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The difference between json and jsonp and the example Analysis of format conversion after obtaining json data through ajax

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The difference between json and jsonp and the example analysis of format conversion after obtaining json data through ajax, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

The difference between json and jsonp (json is the end and jsonp is the means) is described as follows:

In a word, json returns a string of data, while jsonp returns script code (including a function call)

JSON is actually an object in JavaScript, which is exactly the same as var obj= {} in quality, but can be expanded infinitely in quantity. To put it simply, json is actually an object (Object) and an array (Array, which is also an object in JavaScript). This is a good friend where you embed me and you embed n layers of your land, in order to simulate many complex data structures.

Json is easy for people to read and write, and it is also easy to be parsed and generated by machines. The transmission rate is higher than that of the network. The front and back ends of functional websites often exchange a large number of data frequently, while json has gradually become an ideal front-end and back-end data exchange language with its strong expression and high appearance. What about the seniors of xml? I think they should retire like Microsoft's xp.

The front-end and back-end data exchange format under the same origin (children's shoes that do not understand the same origin strategy, please use Baidu) has been determined to use json, so the question is, how can I do it if I want to get the data provided on other people's websites? That is, the problem of reading data across domains (don't say you don't need to read data from other sites, believe me, you will need it sooner or later), how about json? The answer is No Way, why, because json is only a common text format, so you can easily get the server without any security and confidentiality, so the Internet world must be messed up. Those awesome X specification makers have thought of this question for a long time, so they use the same origin strategy to restrict file access. The end result is that only tags such as img, script, and iframe that can specify src attributes have the ability to cross-domain access to data on other people's sites (images, scripts, and source files are actually data). For example:

It seems that it is impossible to get json directly, so is there any other way to get the data? So jsonp was discovered by smart developers, why is it a discovery rather than an invention, because it doesn't involve any new technology, just like discovering ajax.

Jsonp principle is like this, website A needs to obtain the data of website B, website B says I give you a method, [1. You use the tags to get the open.js file (the responsibility of website B), which contains the data you need. two。 The name of your method for obtaining post-processing data (you have to process the data) must be named foo], which is equivalent to the establishment of an agreement between website B and the requestor, requiring the requestor to act in accordance with the rules. If the requester cannot comply with the above two rules at the same time, he or she cannot obtain the data as expected. Well, this is tantamount to establishing an unspoken rule.

Open.js content

Foo ({"name": "B", "age": 23}) / / Why not directly write json data {"name": "B", "age": 23}, the reason is very simple: the js file must conform to the js syntax / / this is why the protocol clearly stipulates that the name of the method for processing data must be named foo, because the B website returns data on the assumption that the data processing method foo has been defined in the requester's script. / / otherwise an foo is not defined error will be reported

Website A script must have

Function foo (data) {console.log (data); / / ToDo.. }

Aah! Although turned a corner, but the data finally got, website A, website B are very happy, then the problem again, website C said that also need to obtain the data of site B, site B threw the protocol to it, site C to take a look, grass mud horse, the name foo has been used in its own script file 6868 lines, and has been used in every corner of the script, batch replacement will lead to a lot of potential bug ah Web site B urgently decided to change foo to fool, and website An immediately jumped up, because his website already used foo to quote data in many places.

In order to avoid the above situation, those awesome developers use the method of dynamically generating js files, and the php version is as follows:

Open.php

Well, as for why php can return the js format file, Baidu itself.

So site An is used to request data without modifying any variables. The content of the script file returned to An is:

Foo ({"name": "B", "age": 23}); / / the so-called jsonp is a function call, and the data is passed to the parameters in a package. Never wear a vest and use it to request data from website C. the content of the script file returned to C is: blah ({"name": "B", "age": 23}). Website N is used to request data, and the content of the script file returned to N is: what ({"name": "B", "age": 23})

Problem Solved, everyone gets the expected data and avoids naming conflicts.

Jsonp's full name is json with padding, which is very vivid, that is, it wraps the json object in a form that conforms to the js syntax so that other websites can request it, that is, it encapsulates the json data into a js file.

Json is an ideal data exchange format, but there is no way to get it directly across domains, so the json padding is passed as an js file in a legitimate js statement. This is the difference between json and jsonp. Json is what you want, jsonp is a common way to achieve this, and of course it is json that is ultimately acquired and processed. So json is the end, jsonp is just the means. Json is always used, while jsonp is only used when obtaining data across domains.

After understanding the difference between json and jsonp, cross-domain data acquisition in ajax is easy to understand and implement. There is nothing special about the same origin, just take it directly, and you need to turn a corner to achieve the goal when cross-domain.

Attach an example of ajax request json data 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 encapsulated jsonp into ajax, which is reasonable, because after all, the vast majority of jsonp requests are ajax. For the specific use of ajax of jquery, please use Baidu. Another point to note is that the $_ REQUEST ['callback'] of the data interface provided by different websites may not necessarily be callback or cb,cbk. Be sure to read the detailed documentation provided by the server about the use of the interface.

Next, I would like to introduce the format conversion after obtaining json data through ajax written by Night Weiyang 0906.

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

A) json obtained by native js through ajax

The data returned at this point is string by default, so you need to use the eval () function to convert it to a json object. You need to pay attention to the format of the string in the function: eval ("(" + data+ ")"). Because the returned string is in {}, eval will recognize the curly braces as the start and end of the js code block, so you must add () to force it to be converted to an object.

B) jquery acquisition

1: make an asynchronous request through ajax () and set type to json, and the json object is returned.

2: the json object is also obtained by using the $.getJSON (url,data1,function (data2,status,xhr) {/ /.}) method equivalent to ajax (). Where data1 is the data sent with the request, and data2 is the data returned by the server, that is, the json object.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report