常见的跨域解决方案以及原理

一、JSONP(适用于单项跨域请求)

原理:因为浏览器对script不存在同源策略,所以script可以跨域请求外部资源,返回的数据是json格式。

缺点:1、只能发送get请求,无法发送post请求

 2、无法判断请求成功还是失败

二、porxy代理

原理:让代理服务器请求目标地址,因为请求是在服务端进行的,在服务端不存在跨域,从而解决跨域问题

实现:将原地址绑定在代理服务器下,让代理服务器发送请求。

三、document.domain

通过js强制改变document.domain为基础主域

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<iframe src="domain2.html"></iframe>
		<script>
			document.domain="127.0.0.1";
			var user="lirunhui";
		</script>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<h1>domain1</h1>
		<h2></h2>
		
		<script>
			document.domain="127.0.0.1";
			console.log(window.parent.user);
		</script>
	</body>
</html>

4、postMessage

在我博客里有篇专门说的postMessage。

postMessage(data,url);
例子:win=window.open("http://jhssdemo.duapp.com/demo/h5_postmessage/win.html");
	win.postMessage('GoogLucky',"http://jhssdemo.duapp.com/");
或者发送给ifram   ifram对象.postMessage(data,url);




windows.addEventListener("message",function(e)//接受数据
{
console.log(e.origin,e.data);
alert("有数据来了");
}
);

猜你喜欢

转载自blog.csdn.net/lirunhui6/article/details/83035459
今日推荐