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.
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.
This is a relatively simple implementation I found:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Top Customers with Callback</title></head><body> <p id="pCustomers"> </p> <script type="text/javascript"> function onCustomerLoaded(result, methodName) { var html = '<ul>'; for (var i = 0; i < result.length; i++) { html += '<li>' + result[i] + '</li>'; } html += '</ul>'; document.getElementById('pCustomers').innerHTML = html; } </script> <script type="text/javascript" src="http://www.yiwuku.com/myService.aspx?jsonp=onCustomerLoaded"></script></body></html>
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!