IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

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

记事本 2010-07-27 23:29:57 累计浏览 4,278 次
本机暂存

将上一篇文章中的代码封装一下,基于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. translateZ() (2026-06-25 21:18:56)
  2. translateY() (2026-06-25 21:17:56)
  3. translateX() (2026-06-25 21:16:01)

查看更多 前端 文章 →

建议继续学习

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