Home > Article > Web Front-end > How does jsonp obtain data across domains? (code example)
How does jsonp obtain data across domains? This article will introduce to you the method of jsonp to obtain cross-domain data. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Jsonp cross-domain data acquisition explanation
Since the browser has a same origin policy, if you want to obtain non-original origin (protocol, domain name , if the three ports are different, they are considered non-original) The data of the page must be cross-domain
(1) jsonp principle
Since the src attribute of the script tag can access non-original js scripts, accessing the server through the src attribute will return the js code of the function, and the data we want is returned as a function parameter, and we will first define this function and return The js code can be executed
(2) jsonp implementation code
Request page
76c82f278ac045591c9159d381de2c57 100db36a723c770d327fc0aef2ce13b1 93f0f5c25f18dab9d176bd4f6de5d30e b2386ffb911b14667cb8f0f91ea547a76e916e0f7d1e588d4f442bf645aedb2f 9c3bca370b5104690d9ef395f2c5f8d1 6c04bd5ca3fcae76e30b72ad730ca86d 8019067d09615e43c7904885b5246f0a function jsonp(data){ console.log(username) } 2cacc6d41bbb37262a98f745aa00fbf0 32c428c1a65afb4c21320ec475b9ffe4 2cacc6d41bbb37262a98f745aa00fbf0 8019067d09615e43c7904885b5246f0a $(document).ready(function(){ var url = "http://www.example.com/jsonp.php?callback=jsonp"; var script = $('3f1c4e4b6b16bbbd69b2ee476dc4f83a053a9cc4c2e9b9f6f911642332d34e85'); script.attr("src",url); $("body").append(script); }); 2cacc6d41bbb37262a98f745aa00fbf0 36cc49f0c466276486e50c850b7e4956 73a6ac4ed44ffec12cee46588e518a5e
7bf6f68ac33b2a6d14a606479bed8015
After that, php will return
jsonp({ name:'niuni })
Then the code h returned by PHP will be executed by the jsonp method of the requested page
(3) jQuery’s simple jsonp cross-domain
<script> function showData (data) { console.info(data); } $(document).ready(function () { $("#btn").click(function () { $.ajax({ url: "http://www.example.comjsonp", type: "GET", dataType: "jsonp",// 返回数据类型 jsonpCallback: "showData",//回调函数 // 获取数据成功就执行success函数 success: function (data) { console.info("data"); } }); }); }); </script>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How does jsonp obtain data across domains? (code example). For more information, please follow other related articles on the PHP Chinese website!