jQuery请求网络(Access-Control-Allow-Origin)

来源:互联网 发布:stc单片机pwm输出频率 编辑:程序博客网 时间:2024/05/01 22:23

如果使用jQuery请求网络遇到这样的问题

XMLHttpRequest cannot load http://www.xx.com. No'Access-Control-Allow-Origin' header is present on the requestedresource. Origin 'null' is therefore not allowed access.

除了在服务端配置外,可以尝试使用一下方式只需在前端设置即可。

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <script src="jquery.min.js"></script>    <script>        $(document).ready(function(){            $("button").click(function(){                $.get("https://crossorigin.me/http://www.w3school.com.cn/example/jquery/demo_test.txt",{//                    dataType: 'JSONP'                },function(responseTxt,statusTxt,xhr){                    if(statusTxt=="success")                        alert("外部内容加载成功!");                        alert(responseTxt);                    if(statusTxt=="error")                        alert("Error: "+xhr.status+": "+xhr.statusText);                });                $.post("https://crossorigin.me/http://www.w3school.com.cn/example/jquery/demo_test.txt",{                 //dataType: 'JSONP'                },function(responseTxt,statusTxt,xhr){                    if(statusTxt=="success")                        alert("外部内容加载成功!");                        alert(responseTxt);                    if(statusTxt=="error")                        alert("Error: "+xhr.status+": "+xhr.statusText);                });                $.ajax({                    url: "https://crossorigin.me/http://www.w3school.com.cn/example/jquery/demo_test.txt",                    useDefaultXhrHeader: false, //important, otherwise its not working                    type: "GET",                    dataType: 'text',                    success: function(response, opts) {alert("success")},                    failure: function(response, opts) {alert("failure")}                });            });        });    </script></head><body><button>向页面发送 HTTP GET 请求,然后获得返回的结果</button></body></html>
0 0