跨域请求的iframe解决方案(2)

记事本 2010-07-27 23:29:57 累计浏览 4,540 次

将上一篇文章中的代码封装一下,基于jQuery。

用法:

// xs的意思是cross site 
$.xsget({ 
  url: "http://127.0.0.1/server.html", 
  callback: function (data) { 
    alert(data); 
  } 
});

源代码:

(function ($) { 
  $.extend({ 
    "xsget": function (options) { 
      $.extend(options, $.xsget.defaults); 
      var iframe = document.createElement("iframe"), 
                same_domain = false; 
      iframe.style.display = "none"; 
      document.body.appendChild(iframe); 
      // 当iframe加载完之后触发的函数 
      function iframe_load() { 
        if (same_domain) { 
          // 调用回调函数 
          if (typeof options.callback === "function") { 
            options.callback(iframe.contentWindow.name); 
          } 
          // 关闭iframe的窗口 
          iframe.contentWindow.close(); 
          // 移除iframe 
          document.body.removeChild(iframe); 
        } else { 
          same_domain = true; 
          iframe.contentWindow.location = options.proxyUrl; 
        } 
      } 
      // 在IE下要用attachEvent来添加iframe的onload事件 
      if (iframe.attachEvent) { 
        iframe.attachEvent("onload", function () { 
          iframe_load(); 
        }); 
      } 
      else { 
        iframe.onload = iframe_load; 
      } 
      iframe.src = options.url; 
    } 
  }); 
  $.extend($.xsget, { 
    "defaults": { 
      // 默认的空白页面,在网站的根目录下 
      proxyUrl: "/empty.html" 
    } 
  }); 
})(jQuery);

同分类推荐文章

  1. Embracing Playful Imperfection With The CSS `random()` Function (2026-11-14 03:10:02)
  2. Document Picture-in-Picture API与任意元素画中画实现 (2026-11-13 17:10:02)
  3. 给博客做个站内全文搜索:纯前端离线倒排索引的设计与取舍 (2026-10-03 16:40:31)

查看更多 前端 文章 →

建议继续学习

  1. jQuery插件---轻量级的弹出窗口wBox. (累计阅读 11,199)
  2. iframe大小自适应 (累计阅读 10,392)
  3. JSON和JSONP的区别 (累计阅读 8,847)
  4. iframe里src="about:blank"的问题。 (累计阅读 8,546)
  5. 优雅绝妙的Javascript跨域问题解决方案 (累计阅读 8,327)
  6. 跨域请求的iframe解决方案(1) (累计阅读 6,793)
  7. ie下iframe输入框焦点丢失解决方案 (累计阅读 6,671)
  8. ajax-cross-domain (累计阅读 6,198)
  9. BO报表系统嵌入Iframe在firefox下的错误修改 (累计阅读 5,986)
  10. 宽带网络运营商劫持网站的技术分析 (累计阅读 5,147)