How to convert the format after ajax obtains json data
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('Content-type: application/javascript'); $jsonCallback = htmlspecialchars($_REQUEST ['callback']); //获取请求者自定义的回调函数名 $jsonData ='{"name":"B","age":23}'; //待返回的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中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

JSON (JavaScriptObjectNotation) is a lightweight data exchange format commonly used for data exchange between web applications. When processing JSON data, we often encounter Unicode-encoded Chinese characters (such as "u4e2du6587") and need to convert them into readable Chinese characters. In PHP, we can achieve this conversion through some simple methods. Next, we will detail how to convert JSONUnico
