Home > Web Front-end > JS Tutorial > A brief analysis of the difference between json and jsonp and the format conversion after obtaining json data through ajax

A brief analysis of the difference between json and jsonp and the format conversion after obtaining json data through ajax

亚连
Release: 2018-05-24 10:46:53
Original
2163 people have browsed it

In a nutshell, json returns a string of data; while jsonp returns script code (including a function call); next, this article will introduce to you the difference between json and jsonp and the format of json data obtained through ajax. For conversion, friends who need it can refer to

The difference between json and jsonp (json is the purpose, jsonp is just the means) is introduced as follows:

In a nutshell, json returns It is a string of data; 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 in quantity Can be infinitely expanded. To put it simply, json is actually an object (Object) and an array (Array, actually an object) in JavaScript. These two good friends are there, you embed me and I embed you in n layers, so as to simulate many complex data structure.

Json is easy for people to read and write, and it is also easy for machines to parse and generate. It has a relatively high network transmission rate. Functional websites often need to exchange large amounts of data frequently on the front and back ends, and JSON relies on its powerful expressiveness and beautiful appearance. Value gradually became the ideal front-end and back-end data exchange language. As for senior xml, I think he should retire like Microsoft's xp.

The front-end and back-end data exchange format under the same origin (children's shoes who don't understand the same origin strategy, please go to Baidu) is determined to use json, so the question is, what if I want to obtain the data provided on other people's websites? Arrive? That is, the problem of reading data across domains (don’t go too far and say that you don’t need to read data from other websites, believe me, you will need it sooner or later). Is json okay? The answer is No Way, why? Because json is just an ordinary text format that allows you to easily get it. The server will have no security and confidentiality at all. In this case, the Internet world will be in chaos. Those awesome people on this issue The specifiers of The final result is that only tags such as img, script, and iframe that can specify the src attribute have the ability to obtain data on other people's websites across domains (pictures, scripts, and source files are actually data). For example:

<!--京东商品图片-->
<img src="http://img30.360buyimg.com/jgsq-productsoa/jfs/t2407/323/1635505465/47386/f2d89d88/56615e00N7a475ee6.jpg" />
<!--百度CDN-->
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
Copy after login

It seems that directly obtaining json is not feasible. Is there any other way to get the data? So jsonp was discovered by smart developers. Why is it said to be a discovery rather than an invention? Because it does not involve any new technology, just like the discovery of ajax.

The principle of jsonp is this. Website A needs to obtain the data of website B. Website B said I will give you a method, [1. You use tag first obtains the open.js file (the responsibility of website B), which contains the data you need. 2. The name of the method you use to process the data after obtaining the data (you have to process the data) must be named foo (responsibility and obligation of the data requester)]. This is equivalent to establishing an agreement between website B and the person requesting the data, requiring The requester must act in accordance with the rules. If the requester cannot comply with the above two at the same time, the data cannot be obtained as expected. Well..., this is equivalent to establishing an unspoken rule.

open.js content

foo({"name":"B","age":23});  //为什么不直接写成json数据{"name":"B","age":23}呢,原因很简单,在js文件总得合乎js语法吧
//这也是为什么协议中明确规定处理数据的方法名必须命名为foo,因为B网站是在假定请求者的脚本中已经定义了数据处理方法foo的情况下返回数据;
//不然就会报foo is not defined错误
Copy after login

Website A script must have

function foo(data){
console.log(data);
//ToDo.. 
}
Copy after login

ah! Although it took a turn, the data was finally obtained. Website A and Website B were very happy. Then the problem came again. Website C said that it also needed to obtain the data of Website B. Website B handed it the agreement, and Website C took it. At first glance, the name foo has been used in line 6868 of its own script file, and has been used in every corner of the script. Bulk replacement will lead to many potential bugs. Website B decided to change foo to Fool, website A jumped up immediately, because its own website has used foo to reference data in many places.

In order to avoid the above situation from happening, those awesome developers used the method of dynamically generating js files. The php version is as follows:

open.php

<?php
header(&#39;Content-type: application/javascript&#39;);
$jsonCallback = htmlspecialchars($_REQUEST [&#39;callback&#39;]); //获取请求者自定义的回调函数名
$jsonData =&#39;{"name":"B","age":23}&#39;; //待返回的json数据
echo $jsonCallback . "(" . $jsonData . ")"; //输出jsonp格式的数据,即一行函数调用语句
?>
Copy after login

Um..., as for why php can return js format files, Baidu.

So website A uses to request data without modifying any variables. , the content of the script file returned to A is:

foo({"name":"B","age":23}); //所谓的jsonp,就是一句函数调用,数据都被包裹传递到参数中了,千万别穿个马甲就不认识了 
网站C就用<script src="http://www.B.com/open.php?callback=blah"></script>来请求数据,返回给C的脚本文件内容是:
blah({"name":"B","age":23}); 
网站N就用<script src="http://www.B.com/open.php?callback=what"></script>来请求数据,返回给N的脚本文件内容是:
what({"name":"B","age":23});
Copy after login

Problem Solved. Everyone has obtained the expected data and avoided naming conflicts.

The full name of jsonp is json with padding, which is very vivid. It is to wrap the json object in a form that conforms to the js syntax so that other websites can request it, that is, to encapsulate the json data into a js file;

Json is an ideal data exchange format, but it cannot be obtained directly across domains, so json is wrapped (padding) in a legal js statement and passed as a js file. This is the difference between json and jsonp. json is what you want, and jsonp is a commonly used method to achieve this purpose. Of course, what is ultimately obtained and processed is json. So json is the purpose and jsonp is just the means. json will always be used, but jsonp will only be used when obtaining data across domains.

After understanding the difference between json and jsonp, in fact, cross-domain data acquisition in ajax is easy to understand and implement. There is nothing special when it comes to the same source. Just get it directly. When it is cross-domain, you need to change it. bend to achieve the goal.

Attached is an example of ajax request json data in jquery:

(同源):

$.ajax({
url:"persons.json",
success:function(data){
    console.log(data);
     //ToDo..
  }
});
Copy after login

(跨域):

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

jquery已把jsonp封装进ajax,很合理,因为毕竟绝大多数的jsonp请求都是ajax,关于jquery的ajax具体用法请自行百度,另外要注意的一点就是不同的网站提供的数据接口的$_REQUEST ['callback']中不一定绝对是callback也可能是cb,cbk等,具体使用时务必阅读服务端提供的有关接口使用的详细文档。

下面给大家介绍下由“夜未央0906”写的通过ajax获得json数据后格式的转换

在有些情况下获取到的json数据可能是string类型的,需要把其格式化为json对象才方便解析。

a)原生js通过ajax获取到的json

  此时返回的数据默认是string型的,所以需要用eval()函数将其转化为json对象。需要注意函数内字符串的格式:eval(“(” + data+“)”),因为返回的string是在{}里面的,eval会将大括号识别为js代码块开始和结束的标志,所以必须加上(),将其强制转化为对象来处理。

b)jquery获取

  1:通过ajax()异步请求并把type设置为json,返回的就是json对象。

  2:通过用与ajax()等价的$.getJSON(url,data1,function(data2,status,xhr){//......})方法获取的也是json对象。其中data1为连同请求发送的数据,data2为服务器返回的数据即json对象。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Ajax请求和Filter配合案例解析

Ajax解决缓存的5种方法总结

ajax快速解决参数过长无法提交成功的问题

The above is the detailed content of A brief analysis of the difference between json and jsonp and the format conversion after obtaining json data through ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template