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

本文介绍了一种通过前端设置来解决跨域请求问题的方法,利用第三方代理服务绕过浏览器的同源策略限制,实现了对不同域资源的成功获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

XMLHttpRequest cannot load http://www.xx.com. No
'Access-Control-Allow-Origin' header is present on the requested
resource. 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值