Javascript 检查http响应代码以显示相应的故障消息
我有一个javascript函数,它获取表单数据并通过http post请求将其发送到服务器。我现在需要检查返回的状态代码是否为201,否则显示错误消息:Javascript 检查http响应代码以显示相应的故障消息,javascript,http-headers,Javascript,Http Headers,我有一个javascript函数,它获取表单数据并通过http post请求将其发送到服务器。我现在需要检查返回的状态代码是否为201,否则显示错误消息: function load(){ console.log(document); var form = document.getElementById("myform"); form.onsubmit = function (e) { // stop the regular form submission e.preventDefa
function load(){
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
}
这通常只是
状态
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function()
if (xhr.readyState == 4 && xhr.status == 201) {
// ^^ request complete ^^ and returned status was 201
}
}
谢谢,我想这正是我想要的!如果我在后面添加一个else If语句来表示If xhr.status!=201,我如何让浏览器显示代码和错误消息?就像您显示任何其他内容一样,在这种情况下,执行类似于
element.innerHTML='error-201'
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function()
if (xhr.readyState == 4 && xhr.status == 201) {
// ^^ request complete ^^ and returned status was 201
}
}