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
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> function jsonp(data){ console.log(username) } </script> <script type="text/javascript" src="jquery-1.8.3.min.js"> </script> <script type="text/javascript"> $(document).ready(function(){ var url = "http://www.example.com/jsonp.php?callback=jsonp"; var script = $('<script><\/script>'); script.attr("src",url); $("body").append(script); }); </script> </body> </html>
<?php $data = {'name': '张三'}; $callback = $_GET['callback']; echo $callback."(".json_encode($data).")"; ?php>
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!