IT技术博客大学习 共学习 共进步

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

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

将上一篇文章中的代码封装一下,基于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. iframe大小自适应 (阅读 9,883)
  2. 优雅绝妙的Javascript跨域问题解决方案 (阅读 7,946)
  3. iframe里src="about:blank"的问题。 (阅读 7,901)
  4. 跨域请求的iframe解决方案(1) (阅读 6,322)
  5. jQuery中getJSON跨域原理详解 (阅读 6,264)
  6. ajax-cross-domain (阅读 5,761)
  7. BO报表系统嵌入Iframe在firefox下的错误修改 (阅读 5,543)
  8. 利用跨域资源共享(CORS)实现ajax跨域调用 (阅读 5,524)
  9. ie下iframe输入框焦点丢失解决方案 (阅读 5,386)
  10. 研究ext发现ajax跨域实现 (阅读 4,702)