Home > Web Front-end > JS Tutorial > In-depth analysis of jsonp protocol principle_json

In-depth analysis of jsonp protocol principle_json

WBOY
Release: 2016-05-16 15:38:02
Original
1985 people have browsed it

Today, in the process of developing joint debugging, we need to obtain data across domains. Because jquery is used, of course, using dataType:'jsonp' can easily solve the problem.
But because the backend did not support jsonp access at the time, he later asked me when implementing this function, what is the format returned in jsonp format? I only knew how to use it, but I couldn't figure out the answer. . .

Although it was solved later, I, who like to solve problems, have always been worried about it. I must research this thoroughly, so I started to read the information, and I felt a sudden enlightenment after seeing it, so I planned to do it Notes to share with everyone.

The difference between JSON and JSONP

Although there is only one letter difference between JSON and JSONP, they are actually not the same thing at all: JSON is a data exchange format, and JSONP is a cross-domain data interaction protocol. What you get using the JSONP method is still It is data in json format.

To put it bluntly, 用JSON来传数据,靠JSONP来跨域.

JSONP explained in detail

We all know, 一个页面的ajax只能获取和此页面同域的数据。, so when we need to obtain data across domains, we need to use the JSONP method to obtain it.

As shown in the figure below, it is the error message returned by using json format to obtain cross-domain data:

So how to solve it? Front-end children's shoes that use frameworks may have their own corresponding methods. For example, jquery can solve it by just adding dataType设为jsonp, but when we use it, have we ever thought about why it can be solved in this way? What is the central idea?

The following is a detailed explanation for you. The first idea is to use scirpt tags to introduce cross-domain data. Let's slowly go into the process of jsonp from the beginning.

Guide Step 1

Writeb.com/b.js Content:

Copy code The code is as follows:
alert(‘hello’);

Then write a.com/a.html content:

Copy code The code is as follows:
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template