What are the best jQuery methods regarding handy Ajax methods and error handling?

Suppose, for example, that I want to partially clone the Gmail interface with jQuery Ajax and do periodic automatic saving as well as sending. And in particular, suppose that I care about error handling, expecting network and other errors, and instead of just being optimistic, I want to handle various errors intelligently.

If I use the "low level" function $ .ajax (), then it clears how to specify the error callback, but the convenient methods $ .get (), $ .post () and .load () do not allow the error callback to be specified.

What are the best methods for pessimistic error handling? Is this by registering .ajaxError () with specific wrapped sets or a global introspection-style error handler in $ .ajaxSetup ()? How do the corresponding parts of the code look like to initiate autosave, so that a warning such as "autosave failed" is displayed if the autosave attempt failed and possibly a message configured to the error type?

Thanks,

+6
javascript jquery ajax
source share
1 answer

It is common practice to use $.ajaxSetup to specify a common callback handler for errors during $.ajax functions. For example.

 function init() { $.ajaxSetup({ error: handleXhrError }); } function handleXhrError(xhr, errorType, exceptionThrown) { // ... } 

Inside handleXhrError you can display either a modal window, or some kind of notification panel, like Gmail, or replace the entire document , depending on the functional requirements. You can take an action based on the response body obtained using xhr.responseText and / or the HTTP status code from xhr.status . The values โ€‹โ€‹of the response body and status can be controlled by the server. They should provide sufficient information about the problem and what actions need to be taken. The value of errorType will be equal to 'timeout' when a timeout occurs (i.e. network problem).

+10
source share

All Articles