跨域

118 阅读1分钟

当有Access to XMLHttpRequest by CORS policy: No 'Access-Control-Allow-Origin' 这些关键字时就代表是跨域错误

跨域解决方案1:CORS跨域资源共享

                            服务端:header("Access-Control-Allow-Origin:*");

                           “*”表示所有的域都可以接受

 跨域解决方案2: jsonp

                             动态创建script标签,使用jQuery的jsonp请求

                             优点:兼容性强&不受同源策略的限制

                             缺点:只能用get方法,不能使用post方法

     

          使用jsonp解决跨域 

        $.ajax({

            url:"http://192.168.1.2/a.php",

            type:"get",

            定义发送jsonp请求

            dataType:'jsonp',

            更改定义的参数名

            jsonp:'kyFn',修改callback名称,但是php中也要修改成相对应的函数名

            指定jsonp发送的回调函数名(可以任意起名字,无需对应)

           


            success:function (res){

                document.write(res);

            }

        });

        function callBack(res){

             document.write(res);

         }

          $.ajax({

             url:"http://localhost:3000",

             success:function(res){

                console.log(res);

            },

             error:function(err){

                 console.log(err)

             }

          })

通过jsonp跨域,原生实现:


script.type = 'text/javascript';

// 传参并指定回调执行函数为onBackscript.src = 'http://www.....:8080/login?user=admin&callback=onBack';

document.head.appendChild(script);

// 回调执行函数function onBack(res) {    

alert(JSON.stringify(res));}

</script>