What is JSONP?

What is JSONP?

What is JSONP? What is JSONP? How to use JSONP?

Firstly, know that...

  1. The core principle of JSONP is to call a local method on the target page, passing in parameters.
  2. Commonly used dynamic pages include JSP, PHP, and ASPX.

Why do we need JSONP?

Data cannot be accessed across domains (including different root domains, second-level domains, or different ports) due to browser security restrictions, unless the target domain authorizes your access. For example, by setting a crossdomain.xml file or authorizing in the HTTP header.

But the crossdomain.xml allows the configured sites to access all data, while header settings are quite麻烦.

So you can set JSONP in your authorized data return to allow all callers to access the data.

The principle of JSONP

JSONP uses the callback principle.

In a web page, if you import another web page's JS, the JS of the page can call your web page's code.

Direct request of JavaScript and the JavaScript code output in dynamic pages (jsp, php, aspx) yield the same effect.

如果引用的js或动态页面里有 showjson({"url":" http://www.bejson.com "});这行代码的话,那就会弹出 http://www.bejson.com

The first method of JSONP, loading the target in JS format, even though it's actually a PHP file.

We will request here on this page. http://www.ibilibili.com/static/js/forbejson/userinfo.php Page data, this PHP page will have a callback function named `showjson` to invoke the `showjson` method in our `bejson` page and pass in a JSON object.

PHP request with callback function:

http://ww3.sinaimg.cn/large/7fa0b485jw1evv94p3v16j20oz09xtb5.jpg

If we capture the packets, as shown in the image, we will see that clicking the button triggers an HTTP request.

Requested // www.bejson.com/test/userinfop.php Page

页面里输出了 showjson({"url":" http://www.bejson.com "}) ,

Because it is Load JavaScript file in format Therefore, it will invoke a callback for the local page showjson (see the green arrow), passing the JSON parameters (see the red arrow), thus displaying the URL from the JSON.

Directly use jQuery's AJAX to request JSONP

Thank you. Gourd Please provide the specific Chinese text that you would like translated into English, and then I will provide you with the translation. Additionally, if you have a specific code snippet in Chinese that you need corrected, please share that as well, and I will provide the corrected code in English.

You recently used:

收藏: favorite Menu QQ