How do you handle errors from AJAX calls?

前端 未结 5 1487
刺人心
刺人心 2020-12-23 14:59

Let\'s say I have the following jQuery AJAX call:

$.ajax({
   type: \"POST\",
   url: \"MyUrl\",
   data: \"val1=test\",
   success: function(result){
               


        
5条回答
  •  误落风尘
    2020-12-23 15:21

    It's pretty late to answer this question but I think It will be beneficial to some one using es6 and jquery 2.2.

    I generally follow this (deferred approach) in my code

    sendAjaxRequest(URL, dataToSend) {
        return $.ajax({
            type        : 'POST',
            url         : URL,
            data        : JSON.stringify(dataToSend),
            dataType    : 'json'
        }).fail((responseData) => {
            if (responseData.responseCode) {
                console.error(responseData.responseCode);
            }
        });
    },
    

    I have attached a deferred fail method which will be called if some error occurs. It is an alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method in latest jquery.

    Next from the place of calling sendAjaxRequest I use then jquery promise callback

    sendAjaxRequest(URL, dataToSend)
    .then(
         (success) => {
         },
         (error) => {
         }
    );
    

    It will call success or error function based on the response received from server.

提交回复
热议问题