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

The principle of Jsonp and its simple implementation method

一个新手
Release: 2017-09-27 10:19:16
Original
2351 people have browsed it


Function

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

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:

<!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 = &#39;<ul>&#39;;            for (var i = 0; i < result.length; i++) {
                html += &#39;<li>&#39; + result[i] + &#39;</li>&#39;;
            }
            html += &#39;</ul>&#39;;
            document.getElementById(&#39;pCustomers&#39;).innerHTML = html;
        }    </script>    <script type="text/javascript" src="http://www.yiwuku.com/myService.aspx?jsonp=onCustomerLoaded"></script></body></html>
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template