jquery ajax忽略500状态错误

oli*_*oli 13 jquery jquery-callback

我正在向App Engine应用程序发出一些GET请求,在Chrome中进行测试.虽然我可以在javascript控制台中看到一些调用导致500服务器错误,但我似乎无法在我的jQuery代码中发现捕获此错误,尽管读取了许多类似的SO线程.我知道它表示服务器端错误,但我仍然希望能够从我的javascript中捕获这样的错误.

我需要捕获错误,以便我可以计算响应的数量(成功或其他),并在收到所有呼叫响应时触发另一个功能.

Chrome控制台输出:

GET http://myapp.com/api?callback=jQuery12345&params=restOfParams 500 (Internal Server Error)
Run Code Online (Sandbox Code Playgroud)

我的电话:

  function makeCall() {
    var count = 0;
    var alldata = $('#inputset').val();
    var rows = alldata.split('\n');
    var countmatch = rows.length;
    for (i=0;i<rows.length;i++) {
      data["param"] = rows[i]["val"];
      $.ajax({
              url: apiUrl,
              type: 'GET',
              data: data,
              dataType: 'jsonp',
              error: function(){
                  alert('Error loading document');
                  count +=1;
              },
              success: function(responseJson) {
                            count +=1;
                            var res = responseJson.results;
                            if (count == countmatch) {
                              allDoneCallback(res);
                            }
                        },
             });
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下一些方法:
添加:

statusCode: {500: function() {alert('err');}}
Run Code Online (Sandbox Code Playgroud)

打电话.

使用:

  $().ready(function(){
     $.ajaxSetup({
       error:function(x,e) {
             if(x.status==500) {
               alert('Internel Server Error.');
             }
           }
      });
   });
Run Code Online (Sandbox Code Playgroud)

有人会就如何捕获500响应提出建议吗?

谢谢奥利

更新:

根据回复,我的jquery代码似乎是正确的,但由于某种原因,它只会捕获从我的应用程序收到的某些500响应.这可能是与App Engine如何返回该错误的问题(我不知道了很多关于这一点),或jQuery的如何处理错误与JSONP -这一点在最后一段简短地讨论这个文章.

我通过使用jquery-isonp来解决这个问题,它抓住了应用程序抛出的所有500个状态.

Mat*_*all 4

您似乎没有document.ready正确使用 jQuery 的绑定。该$().ready(...)版本或多或少已被弃用。请尝试其中之一:

$(document).ready(function() {
    $.ajaxSetup({
        error: function(x, e) {
            if (x.status == 500) {
                alert('Internel Server Error.');
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

简写

$(function() {
    $.ajaxSetup({
        error: function(x, e) {
            if (x.status == 500) {
                alert('Internel Server Error.');
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)