
但是有时候我们确实需要这么做,那么我们有哪些方法呢?
1、JsonP
提到跨域不能不先提及jsonp。jsonp其实是JavacScript Object Notation with Padding的简称,可以理解成填充了内容的json格式数据。
因为以上声明了callback并且调用外域b.com的data.js,而data.js中调用:
callback({msg:"tqtan"});
这样当调用引用外域的js就会调用本地的callback()从而实现数据传输。
上面是只是简单的跨域,我们来看jQuery的真正的运用。
jQuery中的ajax可拉取外域的数据,通过两种方法:
1、$.getJSON()
这种方法简单粗暴,请求外域Json。
复制代码 代码如下:
$.getJSON("http://b.com/dataServlet?callback=?",function(data){
console.log(data.msg);
});
假设上述请求访问b.com下的servlet页面,传的参数为callback=?,jQuery会自动生成字符串填补占位符?,例如callback=jQuery17207481773362960666_1332575486681。这就声明了与服务器的唯一标示,服务器只需要返回带有这个callback值的json格式数据即可,例如:
复制代码 代码如下:
//dataServlet.java
String callback = req.getParameter("callback");
PrintWriter out = resp.getWriter();
out.print(callback+"("msg","tqtan")");
这样就能成功获取非同源服务器的数据了。
2、$.ajax()
实现原理和上面一样,只是可以自定义更多链接。
$.ajax({url:"http://b.com/dataServlet?words=hi",dataType:"jsonp",jsonp : "jsoncallback",jsoncallback : "tqtan",success:function(data){console.log(data.msg);},error: function (e) {console.log(e);}});可以自定义callback的名字,这里改为"tqtan",同时这里可以传值words=hi。//get.htmlvar iframe = document.creatElement("iframe");iframe.src="http://data.a.com/data.html";iframe.style.display="none";document.body.appendChild(iframe);document.domain = "a.com";iframe.onload = function(){var otherDocument = iframe.contentDocument || iframe.contentWindow.document;//otherDocument就是另一个页面的document//do whatever you want..};//data.htmldocument.domain = "a.com";3、url hashvar iframe = document.createElement("iframe");iframe.src = "http://a.com/get.html#data";iframe.style.display = "none";document.body.appendChild(iframe);//周期检测hash更新function getHash() {var data = location.hash ? location.hash.substring(1) : "";console.log(data);}var hashInt = setInterval(function(){getHash()}, 1000);a.com/proxy.htmlparent.location.hash = self.location.hash.substring(1);b.com/data.html//模拟一个简单的参数处理操作if(location.hash){var data = location.hash;doSth(data);}function doSth(data){console.log("from a.com:"+data);var msg = "hello i am b.com";var iframe = document.createElement("iframe");iframe.src = "http://a.com/proxy.html#"+msg;iframe.style.display = "none";document.body.appendChild(iframe);}4、window.namevar state = 0,iframe = document.createElement("iframe"),iframe.src = "http://b.com/data.html";iframe.style.display = "none";loadfn = function() {if (state === 1) {var data = iframe.contentWindow.name;console.log(data);} else if (state === 0) {state = 1;//跳到proxy.htmliframe.contentWindow.location = "http://a.com/proxy.html";}};if (iframe.attachEvent) {iframe.attachEvent("onload", loadfn);} else {iframe.onload = loadfn;}document.body.appendChild(iframe);a.com/proxy.html// proxy.html的操作主要是删除get.html的iframe,避免安全问题发生iframe.contentWindow.document.write("");iframe.contentWindow.close();document.body.removeChild(iframe);b.com/data.htmlvar data = "hello,tqtan";window.name = data;5、 postMessage()var iframe = document.createElement("iframe");iframe.src = "http://b.com/receive.html";document.body.appendChild(iframe);iframe.contentWindow.postMessage("hello","http://b.com");b.com/receive.htmlwindow.addEventListener("message", function(event){// 通过origin属性判断消息来源地址if (event.origin == "http://a.com") {console.log(event.data);console.log(event.source);//发送源的window值}}, false);6、CORS(后台实现)function createCORSRequest(method, url) {var xhr = new XMLHttpRequest();if ("withCredentials" in xhr) {// 此时即支持CORS的情况// 检查XMLHttpRequest对象是否有“withCredentials”属性// “withCredentials”仅存在于XMLHTTPRequest2对象里xhr.open(method, url, true);}else if (typeof!= "undefined") {// 否则检查是否支持XDomainRequest,IE8和IE9支持// XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式xhr = new XDomainRequest();xhr.open(method, url);} else {// 否则,浏览器不支持CORSxhr = null;}return xhr;}var xhr = createCORSRequest("GET", url);if (!xhr) {throw new Error("CORS not supported");}与此同时,服务器端只需要设置Access-Control-Allow-Origin头即可。