检查http响应代码以显示相应的失败消息

时间:2013-11-18 13:21:39

标签: 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.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
  };
};
}

xhr是否有任何具体方法可以做到这一点?我一直在做很多谷歌搜索并遇到这个,但我不认为statusCheck是预定义的吗?

if (statusCheck(server url)) != 201
{
  //do something
}

1 个答案:

答案 0 :(得分:2)

通常只是status

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
    }
}