最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to exit a function in jquery when an error happens in jquery.ajax - Stack Overflow

programmeradmin1浏览0评论

I'woul like to quit my function when an error happens in jquery ajax. for example: if i'm calling $.ajax with a function which has other instructions out of $.ajax and when it es that my $.ajax call has an error, if i try to call return to end up the remaining instructions, those remaining instructions are executed.

So, what i want is to end the whole function from the erro $.ajax parameter.

$.ajax({
 type: "POST",
 url: "home.aspx/ReturnInfoAge",
 data: "{'dD':'" + $('#dDate_wx').val() + "','dM':'" + $('#dMonth_wx').val() + "','dY':'" +   $('#dYear_wx').val() + "'}",
 contentType: "application/json; charset=utf-8",
  dataType: "json",
   success: function (msg) {
    if (msg.d === true) {
       prt.children('.tipCont').remove();
     } else {
       getTooltips(prt, 'criticalv', 'critical', msg.d);
        showMessagingTiming('warning', msg.d, 'Vérification de la date de naissance', null, 5000);
         return;
          }
    },
     error: function (errorMsg) {
       getTooltips(prt, 'criticalv', 'critical', "Veuillez bien saisir la date de naissance.");
      showMessagingTiming('warning', 'Veuillez vérifier: certains champs n\'ont pas les valeurs qu\'il faut.', 'Vérification des champs', null, 5000);
       return;
     }
 })
//other instructions 

I just don't want, if an error happens in $.ajax error parameter to execute the other remaining instructions

I'woul like to quit my function when an error happens in jquery ajax. for example: if i'm calling $.ajax with a function which has other instructions out of $.ajax and when it es that my $.ajax call has an error, if i try to call return to end up the remaining instructions, those remaining instructions are executed.

So, what i want is to end the whole function from the erro $.ajax parameter.

$.ajax({
 type: "POST",
 url: "home.aspx/ReturnInfoAge",
 data: "{'dD':'" + $('#dDate_wx').val() + "','dM':'" + $('#dMonth_wx').val() + "','dY':'" +   $('#dYear_wx').val() + "'}",
 contentType: "application/json; charset=utf-8",
  dataType: "json",
   success: function (msg) {
    if (msg.d === true) {
       prt.children('.tipCont').remove();
     } else {
       getTooltips(prt, 'criticalv', 'critical', msg.d);
        showMessagingTiming('warning', msg.d, 'Vérification de la date de naissance', null, 5000);
         return;
          }
    },
     error: function (errorMsg) {
       getTooltips(prt, 'criticalv', 'critical', "Veuillez bien saisir la date de naissance.");
      showMessagingTiming('warning', 'Veuillez vérifier: certains champs n\'ont pas les valeurs qu\'il faut.', 'Vérification des champs', null, 5000);
       return;
     }
 })
//other instructions 

I just don't want, if an error happens in $.ajax error parameter to execute the other remaining instructions

Share Improve this question edited Oct 26, 2012 at 12:37 Alexis Pigeon 7,51811 gold badges41 silver badges46 bronze badges asked Oct 26, 2012 at 12:11 user1771224user1771224 111 silver badge2 bronze badges 2
  • That ajax function is asynchronous, so by the time you've returned anything from it, the rest of your function has probably long since been pleted. You need to do the other stuff inside the success (done) handler. – adeneo Commented Oct 26, 2012 at 12:14
  • You might want to have a look @ this thread – Jothimurugan B Commented Oct 26, 2012 at 12:36
Add a ment  | 

4 Answers 4

Reset to default 2

error and success callbacks are called asynchronously, so your 'other instructions' starts working before one of those callbacks are called. You should write 'other instructions' into success callback.

function containsAjax() {
    $.ajax({
        type: "POST",
        url: "home.aspx/ReturnInfoAge",
        data: "{'dD':'" + $('#dDate_wx').val() + "','dM':'" + $('#dMonth_wx').val() + "','dY':'" +   $('#dYear_wx').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d === true) {
                prt.children('.tipCont').remove();
            } else {
                getTooltips(prt, 'criticalv', 'critical', msg.d);
                showMessagingTiming('warning', msg.d, 'Vérification de la date de naissance', null, 5000);
            }
            //other instructions should be here.
        },
        error: function (errorMsg) {
            getTooltips(prt, 'criticalv', 'critical', "Veuillez bien saisir la date de naissance.");
            showMessagingTiming('warning', 'Veuillez vérifier: certains champs n\'ont pas les valeurs qu\'il faut.', 'Vérification des champs', null, 5000);
        }
    });
}

If you want to return something from containsAjax function, use callbacks:

function containsAjax(onsuccess, onfail) {
    $.ajax({
        type: "POST",
        url: "home.aspx/ReturnInfoAge",
        data: "{'dD':'" + $('#dDate_wx').val() + "','dM':'" + $('#dMonth_wx').val() + "','dY':'" +   $('#dYear_wx').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d === true) {
                prt.children('.tipCont').remove();
            } else {
                getTooltips(prt, 'criticalv', 'critical', msg.d);
                showMessagingTiming('warning', msg.d, 'Vérification de la date de naissance', null, 5000);
            }
            //other instructions should be here.
            onsuccess(msg);
        },
        error: function (errorMsg) {
            getTooltips(prt, 'criticalv', 'critical', "Veuillez bien saisir la date de naissance.");
            showMessagingTiming('warning', 'Veuillez vérifier: certains champs n\'ont pas les valeurs qu\'il faut.', 'Vérification des champs', null, 5000);
            onfail(errorMsg);
        }
    });
}

And call it like that:

containsAjax(function(msg) {
    // success callback, returns 'msg'
}, function(errormsg) {
    // error callback, returns 'errormsg'
});

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel or abort the request.

var xhr = null;

xhr = $.ajax({
    url : 'path/to/file?some-parameter',
    success : function(responseText) {
        // some DOM manipulation
    }
});

$(document).click(function() { xhr.abort() });

try throw exception

error: function(){
    //...
    throw new Exception('Ajax error description');
}

it will stop everything and also you will see it in debug console

If your function is called on some event then you can use the below statement to abort it. You can write this statement in the error block of your Ajax call.

...
 error: function (errorMsg) {
   event.preventDefault();
   getTooltips(prt, 'criticalv', 'critical', "Veuillez bien saisir la date de naissance.");
   showMessagingTiming('warning', 'Veuillez vérifier: certains champs n\'ont pas les valeurs qu\'il faut.', 'Vérification des champs', null, 5000);
   return;
 }
...
发布评论

评论列表(0)

  1. 暂无评论