Jquery Ajax $ .ajaxError

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

$.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 error conditions are the same. In other words, they all put the phrase "Connection failed" in the msg identifier.

Q1: Can I delete all these files and replace them with

 $().ajaxError(function(myEvent, request, settings, thrownError) { $('#msg').text('Connection error').addClass('err'); }); 

Q2: How could you use myEvent and the query to display a more informative error message?

+4
source share
1 answer

Q1. You can use .ajaxError() as follows:

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

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

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

Q2. You can use the handler arguments that ajaxError passes ajaxError , 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, which is no longer needed, you will need to connect it to the jQuery object you want, or document , if you do not care about a specific element.

+6
source

Source: https://habr.com/ru/post/1306158/


All Articles