Browsing the archives for the ajax tag

Ajax跨域请求

in Develop

这二天在做一个小项目,该小项目中分配出小段的js代码供客户调用。该js代码最终将展现完整的html文档,而且会有Ajax交互。由于Ajax无法跨域,Google了一下到是找到了一些解决方案,但感觉都不大好用。比如加Iframe强制设定document.domain、有使用代理文件。后来看到有朋友在分析zhidao.baidu.com的跨域ajax认证,发现这个方法还是可行的。 原理就是动态在页面的head中添加一段script,该script中会定义一个js变量,页面中就可以调用该js变量了。xxx.xxx中代码可能如下:var v=’这里就是变量啦’; 核心js代码,动态创建script脚本到head中 function request(page, pagesize, appid) { var url = ‘xxx.xxx’; oScript = Find(‘RemoteScript’); var head = document.getElementsByTagName(“head”).item(0); if (oScript) { head.removeChild(oScript); } oScript = document.createElement(“script”); oScript.setAttribute(“src”, url); oScript.setAttribute(“id”,’RemoteScript’); oScript.setAttribute(“type”,”text/javascript”); head.appendChild(oScript); return oScript; } 在调用页的任何区域就可以用变量v了。虽然不是一个很好的解决方案,但感觉也不错了,有一个不足就是必须要等script完全载入之后才可以使用v变量,当然这个也有办法解决。当然,也可以直接用支持跨域的jQuery中的getJson来处理json文件。

8 Comments