【问题标题】:detecting returned errors with $.post使用 $.post 检测返回的错误
【发布时间】:2010-12-29 00:39:10
【问题描述】:

我正在使用 $.post 向 JSP 发送查询,该 JSP 为我返回了一些很棒的数据。

但是,如果查询格式错误,则页面返回“页面错误”和 500 内部服务器错误的 HTTP 状态

在 jQuery 中,我怎样才能检测到这个错误以便告诉用户失败?

 runQuery : function () {
    $.post(
        admin_stats.runQueryURL,
        {
            buster   : Math.random,
            statsQuery: admin_stats.getQuery(),
            jsp: 'admin_statsQuery'
        },
        admin_stats.handleStatsQuery,
        "html"
    );

返回的数据是一个HTML表格,目前对于这个项目来说已经足够了。

另外:如果这是丑陋的或者不是我应该做的事情,完全可以批评=)

【问题讨论】:

  • 喜欢它返回“很棒的数据”

标签: jquery http-post


【解决方案1】:

您需要改用$.ajax 方法:

$.ajax({
    type: 'POST',
    url: admin_stats.runQueryURL,
    data: {
        buster   : Math.random,
        statsQuery: admin_stats.getQuery(),
        jsp: 'admin_statsQuery'
    },
    success: admin_stats.handleStatsQuery,
    error: admin_stats.error, //change this to your handler
    dataType: "html"
});

查看这里了解更多信息:http://api.jquery.com/jQuery.ajax/

【讨论】:

    【解决方案2】:

    看看.ajaxError。来自文档:

    注册一个处理程序以在何时调用 Ajax 请求完成但出现错误。 这是一个 Ajax 事件。

    文档示例:

    $('.log').ajaxError(function(e, xhr, settings, exception) {
      if (settings.url == 'ajax/missing.html') {
        $(this).text('Triggered ajaxError handler.');
      }
    });
    

    如果您想给出特定于返回错误类型的消息,您可以这样做:

    $('.log').ajaxError(function(e, xhr, settings, exception) {
         if(xhr.status == 500) { 
             $(this).text('internal server error');
         } else if (xhr.status == 404) { 
             $(this).text('page not found');
         }
         // etc.
    });
    

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 2018-06-29
      相关资源
      最近更新 更多