gpt4 book ai didi

javascript - Http 状态未在 try 和 catch javascript 上触发

转载 作者:行者123 更新时间:2023-12-02 23:29:50 25 4
gpt4 key购买 nike

我有将 JSON 发布到 API 端点的功能,该功能工作正常。这是我的代码。

function sendValuesPageLoad(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
try {
if (xhr.readyState === 4 && xhr.status === 200) {}
} catch (ex) {
alert('Error parsing response.');
}
}
try {
xhr.open("POST", "test.html?"+encodedString, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
} catch (ex) {
xhr.open("POST", "error.html?"+encodedString, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
}
}

我想要实现的是,如果 xhr.status 不等于 200,则执行进一步的操作。

但是捕获没有被触发。

有人可以帮忙解决这个问题吗?

提前致谢。

最佳答案

XMLHttpRequest 带有自己的错误处理程序 onerror。更新您的示例

function sendValuesPageLoad(){
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
// successful
} else {
// fails
throw new Error('Failed with status: ' + xhr.statusText);
}
}
xhr.onerror = function () {
throw new Error('There is a problem');
}
xhr.open("POST", "test.html?"+encodedString, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
}

您可以通过将其包装在 Promise 中并捕获任何错误来改进这一点

function sendValuesPageLoad(){
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
// successful
resolve(xhr.response);
} else {
// fails
reject(xhr.statusText);
}
}
xhr.onerror = function () {
reject(Error("Network Error"));
}
xhr.open("POST", "test.html?"+encodedString, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
}
}

// use case
sendValuesPageLoad().then(function(response) {
// use your response here
}).catch(function(error) {
// handle your error
});

关于javascript - Http 状态未在 try 和 catch javascript 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56562734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com