跨域的几种方法及案例代码

1、通过动态script实现跨域

function loadScript(url, func) {
				var head = document.head || document.getElementByTagName('head')[0];
				var script = document.createElement('script');
				script.src = url;

				script.onload = script.onreadystatechange = function() {
					if(!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
						func();
						script.onload = script.onreadystatechange = null;
					}
				};

				head.appendChild(script);
			}
			window.baidu = {
				sug: function(data) {
					console.log(data);
				}
			}
			loadScript('http://suggestion.baidu.com/su?wd=w', function() {
				console.log('loaded')
			});
http://suggestion.baidu.com/su?wd=w加载完成后会输出一段字符串
window.baidu.sug({q:"w",p:false,s:["微信网页版","微信公众平台官网","网易云音乐","王者荣耀","微博","wps","微信公众平台","网易邮箱","王牌对王牌","微信公众号"]});

JS代码中已经定义了window.baidu.sug方法,到这里就相当于调用函数了

2、通过domain+iframe方式

a.html

document.domain="a.com"//注意这里
var ifr = document.createElement("iframe");
			ifr.src = "http://www.4008086628.com/iframe.php";
			ifr.style.display = "none";
			document.body.appendChild(ifr);
			ifr.onload = function(){
				var doc = ifr.contentDocument || ifr.contentWindow.document;
				console.log( doc.getElementsByTagName("body")[0].innerHTML );
				ifr.onload = null
			}

b.html

document.domain="a.com"//注意这里

两个页面的主域必须相同,否则无法实现跨域

www.x.a.com/b.html的主域可以设置成x.a.com、a.com或www.x.a.com但不能设置c.www.a.com,因为这是当前域的子域

3、通过window.name

a.html

function getData(){
				var ifr = document.getElementById("ifr");
				ifr.src = "about:blank";
				ifr.onload = function(){
					var data = ifr.contentWindow.name;
					console.log(JSON.parse(data)[0]);
				}
			}
			
			function bywinName(){
				var ifr = document.createElement("iframe");
				ifr.src = "http://www.domain.com/b.html";
				ifr.style.display = "none";
				ifr.id = "ifr";
				ifr.onload = function(){
					getData();//b.html设置的window.name是无法直接获取到的,必须设置成和a.html同源的页面才能获取到
				}
				document.body.appendChild(ifr);
			}
			bywinName();

b.html

window.name = '[{"zhao" : "30"},{"zhou" : "20"},{"li" : "10"}]';

4、通过postMessage实现

a.html

function postMes(){
				var ifr = document.getElementById("ifr");
				var doc = ifr.contentWindow;
				var targetOrigin = "*";
				doc.postMessage("这是来自by-post的信息",targetOrigin);
			}
			function startPost(){
				var ifr = document.createElement("iframe");
				ifr.src = "http://demo.hmrjhj.com/b.html";
				ifr.id ="ifr";
				ifr.style.display = "none";
				ifr.onload = function(){
					postMes();
				}
				document.body.appendChild(ifr);
			}
			startPost();
			window.addEventListener("message",function(event){
				console.log(event.data);
			},false)

b.html

			window.addEventListener("message",function(event){
				console.log(event.data+"hello");
				window.parent.postMessage("已经收到消息","*");
			},false)

5、JSONP

a.html

function getData(res){
				if(!res.errorCode){
					console.log(res.data);
					box.innerHTML = res.data;
				}else{
					console.log(res.errorText);
					box.innerHTML = res.errorText;
				}
			}
			var script = document.createElement("script");
			script.src = "http://www.domain.com/data.php?callback=getData";
			var head = document.getElementsByTagName("head")[0];
			head.appendChild(script)
			var box = document.getElementsByClassName("box")[0];

data.php

header("Content-type: text/html; charset=gb2312"); 
	$callback = $_GET["callback"];
	$data = '{"data" : "zhe"}';
	$error = '{"errorCode" : "404" , "errorText" : "找不到数据"}';
	if($callback==="getData"){
		echo "getData(".$data.")";
	}else{
		echo "getData(".$error.")";
	}	

该方法和通过动态script跨域原理是一样的,理解了那个这个自然就理解了

原文地址:https://www.cnblogs.com/diantao/p/6766860.html