ajax 如何解决跨域问题,我试了试这种方案...

解决问题的灵感来自于:https://segmentfault.com/a/1190000012469713

 

情景一:通过get请求.NET后端获取数据

今天使用ajax跨域请求获取数据,但是报错cors

$.ajax({
    url: "",
    type: "",
    contentType: "",
    dataType: "json",
    success: function (data) {}
})

我尝试多遍后发现,当type为Get,contentType为application/x-www-form-urlencoded、 multipart/form-data、text/plain时,可以获取到数据,.NET后端设置只接受get,所有没有试post请求

浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。只要同时满足以下两大条件,就属于简单请求。

  • 请求方法是以下三种方法之一:HEAD,GET,POST
  • HTTP的头信息不超出以下几种字段:

    • Accept
    • Accept-Language
    • Content-Language
    • Last-Event-ID
    • Content-Type(只限于三个值application/x-www-form-urlencoded、 multipart/form-data、text/plain)

凡是不同时满足上面两个条件,就属于非简单请求。

 

情景二:Post请求php后端添加数据

$.ajax({
    url: "http://api-crm.com:8084/ctrl/ctrl.php?path=bcqz/keyword/keywordAdd.php",
    type: "Post",
    data:params,
    contentType: "application/json",
    dataType: "json",
    success: function (data) {
        debugger
        if (data.IsSuccess) {
            expand_total++
            $("#totals_expand").text( expand_total);
            $(".word_list").append("<span class='ch_index_"+index+"'>"+keywordName+" <small onclick='removeKeyword(\""+keywordName+"\",\""+index+"\")'>×</small></span>");
            $("#table tbody").children().eq(index*1)
            .children(".s_confirm_btn").removeClass("s_confirm_btn").addClass("s_cancle_btn")
            .html("<span  onclick='removeKeyword(\""+keywordName+"\",\""+index+"\")'>取消 </span>");
        } else {
            return false;
        }
    }
});

 此时直接请求会报错 :No 'Access-Control-Allow-Origin' header is present on the requested resource,并且net::ERR_FAILED

解决方法:在被请求的php文件上方添加

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值