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

May 24, 2018 am 10:46 AM
javascript json jsonp

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

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.

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

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.

See all articles