当JavaScript中的Ajax调用不成功时,如何编写错误消息?

时间:2017-07-07 13:08:35

标签: javascript ajax

如果我的Ajax调用失败,我想显示错误消息。很简单,但我无法修改Ajax功能。我创建了一个onClick监听器,在我的AJAX调用成功时执行了一些操作。我打算在电话不成功时做点什么。

所以如果我决定添加:

 if (xhr.status !== 200) {
   //Error Message here
   }

它会放在哪里?

JSFiddle Example Here

我的HTML是:

<div id="test-form">
      <h2>Add a User:</h2>
      <label for="Username:">
       <input id="username" type="text" name="username" placeholder="Type username here">
     </label>

      <label for="Email:">
      <span id='result'></span>
      <input id="email" type="email" name="email" placeholder="email">
      </label>
      <button id="myButton">add user</button>
      <h2 class="clear">Users:</h2>
      <ul id="users"></ul>
    </div>

我的代码是:

 var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '<li>' + username +'</li>';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {


        message.add("hide");
      }

    }



    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });   
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };

3 个答案:

答案 0 :(得分:1)

在不修改函数 addUser()的情况下,看似唯一可行的方法是修改XMLHttpRequest原型,如this answer所示,添加事件 readystatechange 事件的监听器(使用addEventListener())。此外,可以重写onerror函数以检测错误何时导致XMLHttpRequest事务失败。

请记住会影响页面上的所有 XMLHttpRequests!

var lastResponseCode, oldSendFunction;
// store the native send()
oldSendFunction = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function() {
    //subscribe to ready state change events
    this.addEventListener("readystatechange", function(readyEvent) {
        //store the response code, to be checked later
        lastResponseCode = readyEvent.target.status;
    });
    // call the native send()
    oldSendFunction.apply(this, arguments);
}
function onSuccess(result) {
    if (lastResponseCode == 200) {
        //last request was successful
        //...
    }
    else {
         //other response was received - could have been 2xx,3xx,4xx,5xx
    }
}

这保存在this updated plunker中,但似乎不太可能产生200以外的响应代码。要测试失败的XHR请求,请尝试this PHPfiddle,其中每个其他XHR请求都会产生响应代码500

答案 1 :(得分:0)

您可以检查xhr状态,当它不是200时,它就不会成功, 然后你可以抛出responseText。

if (xhr.status !== 200)
    throw(xhr.responseText);

答案 2 :(得分:0)

我想这个问题是要求您在AJAX请求返回错误时显示错误消息,并且不允许您修改addUser()。如果你注意看addUser()函数

  

addUser(用户名,电子邮件,回拨)

在此函数内部,代码显示它们模仿随机故障情况如下:

    var success = (!!Math.round(Math.random()));
    if (!success){
        response = JSON.stringify({
            success: success,
            error: "Oups, something went wrong!"
        });
    } else {
        response = JSON.stringify({
            success: success,
            user: {
                username: username,
                email: email
            }
        });   
    }

所以我认为你可以检查回调函数的响应。响应将随机显示错误或成功。因此,您根本不需要修改addUser()。

function onSuccess(result){
      //check your console to see what is the result first, so you can know how it works
      console.log(result);

      if(result.success){
       // do something
       }else{
       // display error message
   }
}