要检查使用XMLHttpRequest的POST方法是否成功,可以通过监听onreadystatechange
事件并在状态改变时检查readyState
和status
属性。以下是一个基本的示例代码:
var xhr = new XMLHttpRequest();
xhr.open("POST", "your-url-here", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // 4 means request is complete
if (xhr.status === 200) { // 200 means OK status
console.log("POST请求成功,响应数据:", xhr.responseText);
} else {
console.log("POST请求失败,状态码:", xhr.status);
}
}
};
var data = "key1=value1&key2=value2"; // 这里填写你要发送的数据
xhr.send(data);
xhr.open
的第三个参数为false
时,请求会阻塞后续代码的执行。xhr.open
的第三个参数为true
时,请求不会阻塞后续代码的执行。status
不是200,表示请求没有成功。需要检查服务器端的日志来确定具体原因,并进行相应的错误处理。timeout
属性来指定请求的超时时间,并在超时后进行相应的处理。xhr.timeout = 5000; // 设置超时时间为5秒
xhr.ontimeout = function () {
console.log("请求超时");
};
通过上述方法,可以有效地检查和处理XMLHttpRequest POST请求的成功与否。
领取专属 10元无门槛券
手把手带您无忧上云