The most basic principle of JSONP is to dynamically Add a & lt; script & gt; tag, while the src attribute of the script tag has no cross-domain restrictions. In this case, this cross-origin method is not related to the ajaxXmlHttpRequest protocol. During the development of joint debugging today, cross-Origin data retrieval is required. Because jquery is used, of course, dataType: 'jsonp' can be easily used to solve the problem.
However, at that time, the backend did not support jsonp access. Then, when implementing this function, he asked me how the format returned in jsonp format looks like? I have always known how to use it, but I have never answered questions...
Although I solved the problem later, I was always worried about solving the problem. I had to thoroughly study the problem. So I began to read the information and see that there was a clear feeling behind me, so I plan to take a note and share it with you.
Differences between JSON and JSONP
Although JSON and JSONP have only one letter, they are not the same thing at all: JSON is a data exchange format, while JSONP is a cross-domain data exchange protocol, the data obtained using the JSONP method is still in json format.
To put it bluntly,Use JSON to transmit data, and use JSONP for cross-Origin
.
JSONP details
We all know that,Ajax on a page can only obtain data in the same domain as the page.
So we need to use the JSONP method to obtain data across domains.
As shown in, an error message is returned when cross-Origin data is obtained in json format:
How can this problem be solved? Front-end shoes using the framework may all have their own solutions. For example, jquerySet dataType to jsonp
It can be solved, but have we ever thought about it? Why can this problem be solved? What is the central idea?
The following is a detailed description. The primary idea is to use scirpt labels to introduce cross-Origin data. From the very beginning, we gradually went into the jsonp process.
Step 1
Writeb.com/b.js
Content:
The Code is as follows:
Alert ('hello ');
Then writea.com/a.html
Content:
The Code is as follows: