javascript跨域传值的方法及原理

javascript跨域传值的方法及原理

1、location.search

原理:
从a.html根据:window.location.href=”b.html?valus=parm”; 跳转到b.html中,用window.location.search;接收值。
案例:

a.html
	<a href="B.html?name=admin&pwd=123456&sex=男&hobby=篮球">提交</a>
	
b.html
function GetRequest() {
	var url = location.search;
    var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
	}
    return theRequest;
    }
var con = GetRequest();
alert(con.name + ":" + con.pwd + ":" + con.sex + ":" + con.hobby)

2、Ajax

原理:
先创建一个XMLTttpRequest对象,使用XMLTttpRequest对象向服务器发送Ajax请求,向服务器发送Ajax请求的的过程中会使用Ajax引擎进行解析,服务器接收到的经过Ajax引擎解析后的请求内容, 服务器响应后会把请求发送给Ajax引擎,Ajax引擎解析响应后,再将数据呈现在浏览器当中

案例:

var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest(); 
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "username=admin&pwd=admin";
xmlhttp.open("get","http://127.0.0.1:5500/js/test.js",true);
xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
        //console.log("获取完成");
    }
}
xmlhttp.send(data);
$(document).ready(function(){
     $.ajax({
         url:"http://127.0.0.1:5500/js/testa.json",
         type:"get",
         data:{"username":"admin","pwd":"admin"},
         success:function(){
             console.log("成功");
         }
     })
 })

3、 jsonp

原理:
利用src属性进行传值 在传值的过程中使用的是sonp非正式传输协议 利用callback回调函数进行传递和接收数据 在传递过程中用户会传递一个callback参数给服务器,服务器通过call back参数把json的数据在传回给客户端客户端再通过callback函数将json格式的数据解析

案例:

//第一种写法:
<script  type="text/javascript">
    function jsonpCallback(res) {
        console.log(res);
    }
</script>
<script src="http://127.0.0.1:5500/js/testa.jsoncallback=jsonpCallback"> 
</script>

//第二种写法:
<script src="js/jsonp.js"></script>
<script type="text/javascript">
    var s=document.createElement("script")
    s.src="http://127.0.0.1:5500/js/testa.json?callback=test";
    document.getElementsByTagName("body")[0].appendChild(s);
    function jsonpCallback(res) {
        console.log(res);
    }
</script>

4、postMessage

原理:
在主页面中通过postMessage传值给子页面,在子页面通过触发message事件将接收到的数据放在事件对象的data属性中,为兼容多数浏览器需使用JSON.stringify()转化成字符串型

案例:

父页面
//父向子传值
<iframe src="fu.html"></iframe>

window.addEventListener("message",function(res){  
	console.log(res.data);
})

//子向父传值
var win = window.open("http://127.0.0.1:5500/html/zi.html");
setTimeout(function () {
	win.postMessage("父传过来的值", "http://127.0.0.1:5500/html/zi.html")
}, 3000)
window.addEventListener("message", function (res) {
	console.log(res.data)
})

子页面
//父向子传值
window.addEventListener("message",function(res){
	console.log(res.data);
    window.parent.postMessage("子页面穿过来的值","http://127.0.0.1:5500/html/zhu.html")
})

//子向父传值
window.addEventListener("message",function(res){
	console.log(res.data);
    window.opener.postMessage("子传过来的值", "http://127.0.0.1:5500/html/fu.html")
})

5、window.name+iframe

原理:
1、name得值再不同得页面加载后仍然可以存在,可以支持较长得name值(2M)
2、含有window.name的跨域页面在页面加载完后将name值传给与父页面同源的子页面,将iframe中的src值改为同源子页面时window.name值也不会改变 ,这个值就由子页面传给了父页面

案例:

a.html
<iframe src="http://127.0.0.1:5500/html/c.html" frameborder="0" onload="load()" id="iframe"></iframe>
b
let y = true;
function load() {
	if (y) {
		let iframe = document.getElementById("iframe");
		iframe.src = "http://127.0.0.1:5500/html/b.html";
        y = false;
	} else {
		console.log(iframe.contentWindow.name);  //找irrame上window.name的值
	}
}

c.html

window.name="我是score跨域过来的值";

6、document.domain+iframe

原理:
二级域名相同的情况下,两页面都通过js强制设置document.domain为基础主域,使两个页面实现同源,主域同源后,就可以通过iframe进行传值

案例:

a.html
<iframe src="http://b.cc.com/b.html" frameborder="1" onload="load()" id="iframe"></iframe>
//a.cc.com/a.com
document.domain="cc.com";
function load(){
	let iframe=document.getElementById("iframe");
	console.log(iframe.contentWindow.a);
}

b.html

//b.cc.com/b.html
document.domain="cc.com"
var a =10;

7、websocket

原理:
浏览器向服务器发送websocket请求,发送完成链接建立,数据可以在服务器和浏览器之间进行双向传输

案例:

var ws = new WebSocket("wss://echo.websocket.org");
ws.onopen = function () {
	console.log("已建立");
	ws.send("发送数据");
	}
ws.onmessage = function (e) {
	console.log(e.data);
	ws.close();
}
ws.onclose = function () {
	console.log("已关闭")
}   

8、cors

原理:
服务器和浏览器必须同时支持才行**(必须同时使用才行)情况下,使用自定义得http请求让服务器和浏览器进行沟通,从而决定请求是成功还是失败(IE不能低于IE10)**

案例:

浏览器.js
var http = require("http");
var server = http.CreateServer();
server.on('request ', function (req, res) {
    res.setHeader("Access -Control -Allow-0rigin", "* ");
    res.setHeader("Access - Control - Allow-Headers", "Content - Type");
    res.setHeader("Access - control - Allow -Methods", "get");
    res.end("data");
})

浏览器.js
var xm1http = new XMLHttpRequest();
xmlhttp.open("get", "http:/ /www.a. com/test.js", true);
xmIhttp.setRequestHeader("Content -Type", "application/ X - www- form- urlencoded");
xmlhttp.onreadystatechange = function () {
    if (xm1http.readystate == 4 && xmlhttp.status == 200) {
        console.log(xmIhttp.responseText);
    }
}
xmlhttp.send();
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值