跨域原理及解决

解决跨域原理:

首先我们需要理解几点

1jsonp发送的并不是一个ajax请求,是一个script标签

2script标签没有同源策略限制,支持跨域请求

3此时我们将这个script的src指向真实的服务器地址并且携带一个callback=a这样一个参数,后台解析并且返回a这个方法里面包裹着我们需要的数据

4在发送请求前,前台windows中注册a这个方法,之后在a这个方法可以拿到数据

解决方案

1使用第三方库:jsonp    见jsonp的使用:https://blog.csdn.net/github_39274378/article/details/81671313

2 postMessage解决跨域

主要代码

father.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
this is index.html 父页面

<iframe src="http://localhost:8080/child.html" frameborder="0"></iframe>
<script>

    console.log('父页面')
    console.log(window)
    //接收 子页面的通信信息
    window.addEventListener('message',function(e){
        var msg=e.data;
        console.log('从子页面穿过来的消息'+msg);
        if(msg=='1'){
            window.location.href='https://www.baidu.com/'
        }
    },false);

</script>
</body>
</html>

child.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
this is index.html 子页面
<button id="childBtn">点击让父页面跳转</button>
<script>
    console.log('子页面');
    console.log(window);
    childBtn.addEventListener('click',function () {
        alert('click')
        var msg=1;
        window.parent.postMessage(msg,"*");
    })

</script>
</body>
</html>

完整demo:https://github.com/nhclike/iframe-cross-domain

猜你喜欢

转载自blog.csdn.net/github_39274378/article/details/81671363