【问题标题】:why can't I get response of an ajax request while I can get it with normal browser request? [duplicate]为什么我无法通过普通浏览器请求获得 ajax 请求的响应? [复制]
【发布时间】:2016-02-29 18:03:36
【问题描述】:

您好,我正在尝试制作一个 html 文件(不允许使用 PHP),它将向服务器发送一个 ajax 请求,然后提醒响应:

$(document).ready(function(){
$("#connect").click(function(){
$.ajax({
url: "http://213.74.86.200:8080/pwr/relays?ac=123456",
type: "GET",
crossDomain: true,
contentType: 'text/plain',
xhrFields: {
withCredentials: false
},
headers: {
    'Access-Control-Allow-Origin': '*'
},
success:function(data,status){
    if(status=="success"){
    alert(data);
    }else{
        alert("Connection Error");
    }
}   
});
});

});

问题是当我用浏览器打开链接时

http://213.74.86.200:8080/pwr/relays?ac=123456

一切正常,我可以将响应视为文本,但是当我打开我的 html 文件并单击连接按钮时,我在控制台日志中得到了这个:

OPTIONS http://213.74.86.200:8080/pwr/relays?ac=123456

XMLHttpRequest cannot load http://213.74.86.200:8080/pwr/relays?ac=123456.
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access. The response had
HTTP status code 405.

有什么帮助吗?

【问题讨论】:

    标签: javascript jquery html ajax


    【解决方案1】:

    正如错误所说,您需要在relays 页面上设置Access-Control-Allow-Origin

    【讨论】:

    • 那为什么我从浏览器打开链接时不需要它?我认为 ajax 与普通浏览器请求相同!
    • @FareedNema — 因为,正如重复的问题所说,当你直接打开它时,它只是在你和站点 A 之间。它不在你、站点 A 和一些不受信任的第三方 JavaScript 之间在站点 B 上。
    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2021-12-24
    • 1970-01-01
    • 2013-10-22
    • 2011-08-17
    • 2022-09-30
    相关资源
    最近更新 更多