【问题标题】:How to properly try and Catch in jQuery如何在 jQuery 中正确尝试和 Catch
【发布时间】:2016-01-26 02:27:45
【问题描述】:

我有以下函数,它从 Web 服务获取响应。响应应该显示在网站的一个部分。 这很好,但问题是,如果出现错误,我会尝试获取错误消息并以与成功响应相同的方式显示它,但我无法得到。

$(document).ready(function(){
$('.button').click(function(){
    try {
        var $resp = $.get("service url here", function(resp){
        $('.response').append(resp.response.greeting + ", " + resp.response.Welcome);
        });
    }
    catch (err){
        $('.response').append(err.name + ", "+ err.message);
    }

    });
});

【问题讨论】:

标签: javascript jquery web-services error-handling try-catch


【解决方案1】:

尝试使用.always()

$(document).ready(function(){
  $(".button").click(function() {
    $.get("service url here")
    .always(function(resp, textStatus, jqxhr) {
        $(".response")
        .append(textStatus === "success" 
          ? resp.response.greeting + ", " + resp.response.Welcome
          : textStatus + ", "+ jqxhr
        );    
    });
});

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 2014-07-07
    • 2019-07-06
    • 2014-12-22
    • 2013-11-04
    • 2012-02-26
    • 2017-02-13
    • 2015-10-04
    • 2018-10-10
    相关资源
    最近更新 更多