jQuery $ .post可以从回调中再次调用自己吗?

时间:2012-01-21 23:30:30

标签: ajax jquery

用例是如果它得到的响应不是它想要的,它可以再次调用自己。

$.post(qrLoginAjax.ajaxurl, { 
    userID : '11234324'
},function( response ) {
    if (response.userID != 'undefined'){
        //do stuff
    } else {
        // call $.post again
    }
});

我该怎么做?

由于

3 个答案:

答案 0 :(得分:3)

你可以这样做:

var sendAjax = function() {
    $.post('/foo', function(result) {
        if (response.userID != 'undefined') {
            // do stuff
        } else {
            // resend the AJAX request by calling the sendAjax function again
            sendAjax();
        }
    });
};

sendAjax();

但在我看来,发送这样的AJAX请求似乎是一个糟糕的设计决定。您应该确保不会通过使用多个重试计数器来进行无限递归。

答案 1 :(得分:1)

你可以使它成为一个功能,并自行调用。例如,使用$ .ajax,您可以这样做:

function do_stuff(){
    $.ajax({
        url: 'ajax.php',
        success: function(data){
            // Stuff
        },
        error: function(){
            do_stuff();
        }
    });
}

这是递归函数的一般原则,但强烈建议您测试条件或设置最大尝试次数,以免它陷入无限循环。

答案 2 :(得分:0)

使用Java的this关键字。众所周知,这是指它所属的对象。例如:

$.post(qrLoginAjax.ajaxurl, 
      {
        userID : '11234324'
      }, 
      function( response ) {
          if (response.userID != 'undefined') {
             //do stuff
          } 
          else {
            $.post(this);
          }
      }
);