Home  >  Article  >  Web Front-end  >  How to convert the format after ajax obtains json data

How to convert the format after ajax obtains json data

php中世界最好的语言
php中世界最好的语言Original
2018-04-24 17:24:052593browse

This time I will show you how to convert the format after ajax obtains json data. What are the precautions for format conversion after ajax obtains json data. The following is a practical case, let's take a look.

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 how to obtain json through ajax. For the conversion of data format, 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 a string of data; jsonp returns script code (including a function call);

JSON is actually an object in JavaScript, with var obj={} Qualitatively exactly the same, but quantitatively infinitely expandable. 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>

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错误

Website A script must have

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

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格式的数据,即一行函数调用语句
?>

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});

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

jsonp全名叫做json with padding,很形象,就是把json对象用符合js语法的形式包裹起来以使其它网站可以请求得到,也就是将json数据封装成js文件;

json是理想的数据交换格式,但没办法跨域直接获取,于是就将json包裹(padding)在一个合法的js语句中作为js文件传过去。这就是json和jsonp的区别,json是想要的东西,jsonp是达到这个目的而普遍采用的一种方法,当然最终获得和处理的还是json。所以说json是目的,jsonp只是手段。json总会用到,而jsonp只有在跨域获取数据才会用到。

理解了json和jsonp的区别之后,其实ajax里的跨域获取数据就很好理解和实现了,同源时候并没有什么特别的,直接取就行,跨域时候需要拐个弯来达到目的。

附上jquery中ajax请求json数据实例:

(同源):

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

(跨域):

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

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对象。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Ajax实现loading等待效果提高用户体验

Ajax使用步骤详解

jQuery使用ajax跨域获取数据步骤详解

The above is the detailed content of How to convert the format after ajax obtains json data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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