通过JSONP实现完美跨域
什么是JSONP
JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求,我们可以通过使用 html的script标记来进行跨域请求,并在响应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式称为JSONP。
对于上面的解释,我们可以简单这样理解:JSONP就是可以通过JavaScript文件进行跨域通讯的方式,例如:现在各大网站风靡的搜索提示,搜狗云输入法
注意:JSONP服务器端代码需要充分做好安全措施。
最简单的JSONP
var JSONP = document.createElement("script") ;//FF:onload IE:onreadystatechangeJSONP.onload = JSONP.onreadystatechange = function(){//onreadystatechange,仅IEif (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {alert($("#demo").html());JSONP.onload = JSONP.onreadystatechange = null//请内存,防止IE memory leaks}}JSONP.type = "text/javascript";JSONP.src = "http://a.pojaaimg.cn/2010/js/jquery.js";//在head之后添加js文件document.getElementsByTagName("head")[0].appendChild(JSONP);
function jsonpHandle(a){ alert(a);}var JSONP = document.createElement("script") ;JSONP.type = "text/javascript";JSONP.src = "http://www.js8.in/jsonp.php?callback=jsonpHandle";//在head之后添加js文件document.getElementsByTagName("head")[0].appendChild(JSONP);
echo $_GET["callback"]."('hello,world')";