技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> 跨域请求的iframe解决方案(2)

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

浏览:3095次  出处信息

将上一篇文章中的代码封装一下,基于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大小自适应    (阅读:8607)
  2. iframe里src="about:blank"的问题。    (阅读:6778)
  3. 优雅绝妙的Javascript跨域问题解决方案    (阅读:6681)
  4. jQuery中getJSON跨域原理详解    (阅读:5542)
  5. 跨域请求的iframe解决方案(1)    (阅读:5309)
  6. ajax-cross-domain    (阅读:4920)
  7. BO报表系统嵌入Iframe在firefox下的错误修改    (阅读:4564)
  8. ie下iframe输入框焦点丢失解决方案    (阅读:4217)
  9. 利用跨域资源共享(CORS)实现ajax跨域调用    (阅读:4066)
  10. 研究ext发现ajax跨域实现    (阅读:3679)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1