Home  >  Article  >  Web Front-end  >  The principle of Jsonp and its simple implementation method

The principle of Jsonp and its simple implementation method

一个新手
一个新手Original
2017-09-27 10:19:162173browse


Function

Jsonp是json的一种使用模式,用来解决主流浏览器的跨域数据访问的问题.因为同源策略,页面是无法直接与其他不同源的页面沟通的.利用Script元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。

Same origin: refers to the same protocol, domain name, and port. When the browser page executes a script, it will check which page the script belongs to. Only scripts with the same origin as this page will be executed, otherwise the console will report an error.

Principle

Use the Script tag on the client to obtain data in Jsonp format (data captured using JSONP It is not JSON, but arbitrary JavaScript, executed with a JavaScript interpreter rather than parsed with a JSON parser), and at the same time executes a jsonp callback function. To execute this callback function, you must first define the callback function on the client.

Simple implementation

This is a relatively simple implementation I found:


    Top Customers with Callback

For example, if a customer wants to visit http://www.yiwuku.com/myService.aspx? jsonp=callbackFunction
Assume that the customer expects to return JSON data: ["customername1","customername2"]
Then the Script Tags actually returned to the client: callbackFunction(["customername1","customername2"])

The above is the detailed content of The principle of Jsonp and its simple implementation method. 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