【发布时间】:2019-06-12 23:42:20
【问题描述】:
我有将 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,我想要实现的是执行进一步的操作。
但是捕获没有被触发。
有人可以帮忙吗?
提前致谢。
【问题讨论】:
-
如果状态不是
200,您可以使用throw。 -
你为什么期望它被触发?不能例外
-
@randomSoul 不明白你的意思。您可以编辑我的代码作为示例吗?
-
对于您当前的代码没有例外,因此它不会执行您的
catch块。如果你想在状态不是200的情况下执行你的catch块。您可以添加 if 语句来检查是否状态不是 200,然后在其中使用 throw 语句,这样您的catch块就会被执行。
标签: javascript html json xmlhttprequest