http返回html成功,带有HTTP请求的HTML:始终返回0

请求完成之前,您正在查看xhr.status。仅在status为readyState时检查4:

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {

if (xhr.readyState == 4) {

if (xhr.status >= 200 && xhr.status < 300) {

// All good

console.log(xhr.status);

}

else {

// Something went wrong

alert(xhr.status);

}

}

}

xhr.open('GET', "http://localhost:8080/hello", true);

xhr.send();

也就是说,在所有主流浏览器上,XMLHttpRequest已过时。而是使用fetch:

fetch("http://localhost:8080/hello")

.then(response => {

if (!response.ok) {

throw new Error(response.status);

}

})

.then(response => {

// Read the body of the response

return response.text(); // or .json(), .arrayBuffer(), .blob(), .formData()

})

.then(data => {

// All good, use the data

})

.catch(error => {

// Handle the error

});

如果愿意,可以使用.text(它是ReadableStream)代替.json,response.body等助手。

您说过,更新后的代码仍处于0状态。我能看到的唯一方法是,如果您正在发出跨域请求,并且受到Same Origin Policy的阻止。您应该在Web控制台中得到一个非常明确的错误。如果是这种情况,请查看CORS(如果您控制另一端)或JSONP或使用服务器为您发出请求。那里有很多有关SOP和CORS的信息。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值