显示每个错误代码的响应代码

时间:2014-07-17 22:14:27

标签: jquery ajax

我试图做的是显示不同的错误消息,响应代码200400404408& 500但是,我不认为我做得对。

我看了一眼:jQuery AJAX Error Handling (HTTP Status Codes)但仍然感到困惑......

我下面的内容可能很乱,但是有什么指导吗?

            var request;  //make request object a global variable
            function getAJAX(){
              request = new XMLHttpRequest();
              request.open("GET", "file.txt");
              request.onreadystatechange = checkData;
              request.send(null);
            } // end function\

            function getYo(){
              request = new XMLHttpRequest();
              request.open("GET", "file2.txt");
              request.onreadystatechange = checkDataa;
              request.send(null);
            } // end function

            function checkData(){
              if (request.readyState == 4) {
                // if state is finished
                if (request.status == 200) {
                  // and if attempt was successful
                  alert(request.responseText);
                } // end if
              } // end if
            } // end checkData

            function checkDataa(){
              if (request.readyState == 4) {
                // if state is finished
                if (request.status == 400) {
                  // and if attempt was successful
                  alert(request.responseText);
                } // end if
              } // end if
            } // end checkData

2 个答案:

答案 0 :(得分:0)

您可以在两者中创建一个简单的函数并传入状态(以及您可能想要的任何其他内容):

function errorAlert( status ){
   var msg;
   switch(status}{
      case 404:
         msg  = "Ooooops can't find it!";
       break;
       default:
          msg = 'unknown error';
   }
   alert( msg );
}

然后在你的请求回调中

if (request.readyState == 4) {
   if( request.status !== 200){
         errorAlert(  request.status );
         /* quit here */
         return;
   }
    /* handle response here */
}

这显然是相当原始的,但应该让你知道如何构建它

答案 1 :(得分:0)

利用jquery $.ajax() statusCode设置对象,回调函数,试试

修改,更新

html,例如,

<button id="error">error</button>
<button id="success">success</button>

JS

$(function() {
    var urls = ["file.txt", "file1.txt"];
    var request = function (url) {
        return $.ajax({
        url : url, 
        type : "GET",
        statusCode : {
            200 : function (data, textStatus, jqxhr) {
                    alert(data);
            },
            403 : function (jqxhr, textStatus, errorThrown) {
                    alert(textStatus + "\n" + errorThrown);
            },
            404 : function (jqxhr, textStatus, errorThrown) {
                    alert(textStatus + "\n" + errorThrown);
            }
        }
    });
    };

$("button#error").on("click", function(e) {
    request(urls[0]);
});
$("button#success").on("click", function(e) {
    request(urls[1]);
});

});

jsfiddle http://jsfiddle.net/guest271314/XSQ3w/