小言_互联网的博客

JS中 跨域

337人阅读  评论(0)
一、什么是跨域

1. 同源政策
该政策是针对浏览器的,不是针对JS的。浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能读写对方的资源。
2. 跨域
指通过js在不同的域(不同源)之间进行数据传输或通信,实现资源共享。
不同源有三种情况:协议不同、 端口不同、 域名不同

二、跨域的方式

Access-Control-Allow-Origin 出现跨域访问
1. jsonp跨域
jsonp 跨域原理是通过src + callback回调函数来请求

     function method(med, api, async, data, callback) {
        var http = new XMLHttpRequest();
        if (med == "get") {
            if (data) {
                api += "?";
                api += data;
            }
            http.open(med, api, async);
            http.send();
        }
        else {
            http.open(med, api, async);
            if (data) {
                http.send(data);
            }
            else {
                http.send();
            }
        }

        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.response);
            }
        }
    }
</script>
<script>
    function getData(res){
        console.log(res);
    }
</script>
<script src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData" type="text/javascript"></script>

优点:
直接访问相应文本,支持在服务器与浏览器之间的双向通信。
缺点:
因jsonp是在其他域中加载代码执行,如果其他域不安全,可能会在响应中夹带一些恶意代码;另外确定请求成功或失败并不容易。
2. cors跨域

    function method(med, api, async, data, callback) {
        var http = new XMLHttpRequest();
        if (med == "get") {
            if (data) {
                api += "?";
                api += data;
            }
            http.open(med, api, async);
            /*http.setRequestHeader("header","Access-Control-Allow-Origin:*");
            http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");*/
            http.send();
        }
        else {
            http.open(med, api, async);
            if (data) {
                http.send(data);
            }
            else {
                http.send();
            }
        }

        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.response);
            }
        }
    }
    //  cros  在php文件里面配 header('Access-Control-Allow-Origin: * ');
    /*var src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData";
    method("get", src, true, "", function (result) {
        console.log(result);
    })*/
</script>
<script>
    function getData(res){
        console.log(res);
    }
</script>
<script src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData" type="text/javascript"></script>

转载:https://blog.csdn.net/jingerh126/article/details/101030786
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场