开发者

jquery Ajax $.ajaxError

开发者 https://www.devze.com 2022-12-25 16:05 出处:网络
I have a bunch of ajax calls that contain success and error conditions like this one: $.ajax({ url: \'Remote/State.cfc\'

I have a bunch of ajax calls that contain success and error conditions like this one:

    $.ajax({
        url: 'Remote/State.cfc'
        ,type: "POST"
        ,data: {
            'method': 'UpdateStateName'
            ,'StateID': StateID
            ,'StateName': StateName
        }
        ,success: function(result){
            if (isNaN(result)) {
                $('#msg').text(result).addClass('err');
            } else {
                $('#' + result + ' input[name="StateName"]').addClass('changed');
            };
        }
        ,error: function(msg){
            $('#msg').text('Connection error').addClass('err');
        }
    });

All the error conditions are the same. In other words, they all put the phrase "Connection error" in the msg id.

Q1: Could I remove all these and replace them with

$().ajaxError(function(myEvent, request, s开发者_如何学Cettings, thrownError) {
    $('#msg').text('Connection error').addClass('err');
});

Q2: How would you use myEvent and request to display a more informative error message?


Q1. You can use .ajaxError() like this:

$(document).ajaxError(function() {
  $('#msg').text('Connection error').addClass('err');
});

...or if the #msg element is present the entire time, you can do this:

$('#msg').ajaxError(function() {
  $(this).text('Connection error').addClass('err');
});

Q2. You can use the handler's arguments that ajaxError passes in, it uses this format: handler(event, XMLHttpRequest, ajaxOptions, thrownError), something like this:

$(document).ajaxError(function(event, request, options, error) {
  $('#msg').addClass('err')
     .text('Connection error: ' + error + ' when connecting to ' + options.url);
});

Note: in previous versions of jQuery this would be done via $.ajaxError(), since 1.7 that's no longer the case, you'll need to attach it to a jQuery object you want it on, or document if you don't care about a particular element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号