异步跨域访问的几种方式

来源:互联网 发布:js banner轮播 编辑:程序博客网 时间:2024/05/22 14:49

废话不说,直接进入主题吧:
第一种:代理
具体做法是在本地服务器建立一个代理脚本(如PHP),这个脚本可以将接收到的数据(GET或者POST)通过CURL(或者还有其他的方式)发送到目的服务器。
第二种:隐藏框架
现在通常使用的是iframe。
第三种:动态IMG标签
这种方法简单,适合那种只是需要往服务器端发送信息的场合(如PV统计,点击统计等)
  1. var tmp = new Image();
  2. tmp.src = "{your url}";   //把要传递的信息加到url中
第四种:动态SCRIPT标签
具体做法看下面的代码:
  1. // Constructor -- pass a REST request URL to the constructor
  2. //
  3. function JSONscriptRequest(fullUrl) {
  4.     // REST request path
  5.     this.fullUrl = fullUrl; 
  6.     // Keep IE from caching requests
  7.     this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
  8.     // Get the DOM location to put the script tag
  9.     this.headLoc = document.getElementsByTagName("head").item(0);
  10.     // Generate a unique script tag id
  11.     this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
  12. }
  13. // Static script ID counter
  14. JSONscriptRequest.scriptCounter = 1;
  15. // buildScriptTag method
  16. //
  17. JSONscriptRequest.prototype.buildScriptTag = function () {
  18.     // Create the script tag
  19.     this.scriptObj = document.createElement("script");
  20.     
  21.     // Add script object attributes
  22.     this.scriptObj.setAttribute("type""text/javascript");
  23.     this.scriptObj.setAttribute("charset""utf-8");
  24.     this.scriptObj.setAttribute("src"this.fullUrl + this.noCacheIE);
  25.     this.scriptObj.setAttribute("id"this.scriptId);
  26. }
  27.  
  28. // removeScriptTag method
  29. // 
  30. JSONscriptRequest.prototype.removeScriptTag = function () {
  31.     // Destroy the script tag
  32.     this.headLoc.removeChild(this.scriptObj);  
  33. }
  34. // addScriptTag method
  35. //
  36. JSONscriptRequest.prototype.addScriptTag = function () {
  37.     // Create the script tag
  38.     this.headLoc.appendChild(this.scriptObj);
  39. }
一个使用的例子:
  1. function callbackfunc(jsonData) {
  2.      alert('Latitude = ' + jsonData.ResultSet.Result[0].Latitude + 
  3.            '  Longitude = ' + jsonData.ResultSet.Result[0].Longitude);
  4.      aObj.removeScriptTag();
  5. }
  6. request = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo
  7.            output=json&callback=callbackfunc&location=78704';
  8. aObj = new JSONscriptRequest(request);
  9. aObj.buildScriptTag();
  10. aObj.addScriptTag();
经过测试,上面的方法的确可以进行跨域访问,但是有几个问题:
1,请求的时候需要调用三个方法,而这三个方法显然是可以封装在一起的。
2,在callback函数中居然还要调用removeScriptTag方法,这是我最不希望看到的。
3,在遨游浏览器中callback无效。(在IE7上没有问题,但是一切换到遨游上测试就无效,至今还搞不清楚是怎么回事。后来延迟一下执行请求的函数居然就可以了,相当于延迟执行上面的第9~11行代码)
4,学习了jQuery的源码之后,显然对这种写法很不满。
自己尝试封装如下(注:还没有经过充分测试,呵呵):(点击下载)
 
使用方法如下:
  1. function callback(data){
  2.     //your code
  3. }
  4. url = 'your url';
  5. JSRQuery(url,callback); //如果没有回调函数可以这样: JSRQuery(url);
这样使用起来就简单多了。
PS:在jquery源码里有出现过很多jsonp,上网一查据说是JSON with Padding的简称(见:http://www.cn-cuckoo.com/2008/09/13/the-origin-of-jsonp-262.html

原创粉丝点击