What is JSONP? What is JSONP? How to use 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.
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.
function showjson(json){
alert(json.url);
}
如果引用的js或动态页面里有 showjson({"url":" http://www.bejson.com "});这行代码的话,那就会弹出 http://www.bejson.com
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
// This is a PHP page, calling the showjson method, which must match the callback method defined in the local page above.
echo 'showjson({"url":"http://www.bejson.com"})';
?>
PHP request with callback function:
$("#getuserp").click(function(){
$.getScript("//www.bejson.com/test/userinfop.php");
});
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.
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.
x $.ajax({
url:'//www.bejson.com/test/userinfop.php',
type:"GET",
dataType:"jsonp",
jsonp: false,
jsonpCallback: "showjson", // The value here should match the name of the callback function.
success:function(data){
console.log("Script loaded and executed.");
},
error:function (textStatus) { // Function called after a request fails
console.log(JSON.stringify(textStatus));
}
});
You recently used: