标签:
参考:http://blog.csdn.net/joyhen/article/details/21631833
方法1: 该方法不同于ajax,因为script标签不受同源策略的限制。
前端和后台需要约定一个接收参数, 然后返回一段js代码。
后端php代码:
<?php $callback = $_GET[‘callback‘]; $json = ‘{"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6c5f\u82cf","city":"\u82cf\u5dde","district":"","isp":"","type":"","desc":""}‘; header(‘content-type: text/javascript‘); echo $callback . ‘(‘ , $json, ‘);‘;
// url: https://animals-facial.c9users.io/json.php?_callback=_callback123
//输出:_callback123({"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6c5f\u82cf","city":"\u82cf\u5dde","district":"","isp":"","type":"","desc":""});
//输出了一段js代码
后台输出一段js代码,其中包含了一个 _callback123 的方法,参数是一个object。
前端代码:
<script> //动态创建一个script function loadScript(url, data, fun) { var head = document.head || document.getElementsByName("head")[0], scriptElement = document.createElement("script"),
//把传入的值设置成随机的。 funName = ‘_callback‘ + Math.round(Math.random() * 1000); //使用约定的callback为参数, fullName是传入callback参数的值 url = url + ‘?callback=‘ + funName; //把参数接到URL后面 for (var i in data) { url += ‘&‘ + i + ‘=‘ + data[i]; } scriptElement.src = url; //取到js方法后,执行该js方法。 这里要用全局的方法,所以用window[] window[funName] = function (json) { fun(json); //执行完成后删除该script和该方法 head.removeChild(scriptElement); window[funName] = null; }; scriptElement.onload = function () { scriptElement.onload = scriptElement.onreadystatechange = null; } head.appendChild(scriptElement) } //传入url, 数据, 回调函数 loadScript("https://animals-facial.c9users.io/json.php", { name: ‘china‘ }, function (json) {
//todo something console.log(json); 输出得到的json }); </script>
标签:
原文地址:http://www.cnblogs.com/facial/p/5851473.html