将上一篇文章中的代码封装一下,基于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); |