代码之家  ›  专栏  ›  技术社区  ›  Ted

如何根据初始.ajax调用的结果启动另一个jQuery.ajax调用?

  •  0
  • Ted  · 技术社区  · 15 年前

    我有一个jQuery.ajax调用:

    $j.ajax({
        type: "POST",
        url: "/Services/Cart.asmx/UpdateQuantity",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            var d = msg.d;
            // etc.
        },
        error: function(xhr, msg) {
            var response = JSON.parse(xhr.responseText);
            var cart = $j('#cart');
            if (response.Message) {
                cart.before('<div class="error">' + response.Message + '</div>');
            } else {
                cart.before(' <div class="error">An unexpected error occurred.</div> ');
            }
        },
        complete: function(request, settings) {
            // Some other stuff.
        }
    
    }); // end ajax
    alert('Initially thought this would be called after above .ajax call complete. But it is not. Rather, it is called before success etc.');
    

    但是,基于第一个ajax调用返回的一些数据,我想启动第二个.ajax调用。尽管如此,由于回调是如何为第一个回调配置的,它并不是按顺序发生的(即,在上面的最后一个警报('Initially…')行中的位置),因此我无法使用最新更新的客户端DOM数据。

    再打一个ajax电话怎么样?我很快在整个活动中做了一些测试,但似乎没有成功。

    我已经有了“jQuery在运行”坐在这里等着我找时间钻研它,以了解引擎盖下发生的更多事情,但还没有时间!

    更新:Erk。当显而易见的事情没有像预期的那样首先发生作用时,问题通常出现在椅子和显示器之间;我要把这个放一个通宵的脑屁。事实证明,我最初是如何设置的(在成功回调中调用第二个.ajax调用)显然是正确的,但我的第二个.ajax调用中有一个小语法错误(因此失败并使我走错了方向)。

    @kgiannakakis被认为是答案,因为他/她是a)第一个和b)提供了可笑的低调“您可以将调用配置为同步,但这不是推荐的技术。”

    2 回复  |  直到 6 年前
        1
  •  3
  •   landyman    15 年前

    如果您想根据第一个请求的结果发出另一个ajax请求,那么在另一个函数中可能应该有第二个ajax请求。另一个函数将在第一个ajax请求的成功事件中被调用。

    $j.ajax({
        type: "POST",
        url: "/Services/Cart.asmx/UpdateQuantity",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: newSuccessFunction(xhr,msg),
        error: function(xhr, msg) {
            var response = JSON.parse(xhr.responseText);
            var cart = $j('#cart');
            if (response.Message) {
                cart.before(' <div class="error">' + response.Message + '</div> ');
            }
            else {
                cart.before(' <div class="error">An unexpected error occurred.</div> ');
            }
        },
        complete: function(request, settings) {
            // Some other stuff.
        }
    
    }); // end ajax
    
    function newSuccessFunction(xhr,msg) {
        var d = msg.d;
        //... etc.
        $.ajax({ //...
               });
        alert('Initially thought this would be called after above .ajax call complete. But it is not. Rather, it is called before success etc.')
    }
    
        2
  •  2
  •   kgiannakakis    15 年前

    警报应该放在成功回调中,而不是在ajax调用之后。ajax调用的默认行为是异步的。也就是说,调用立即返回,并在稍后的某个时间点调用回调,即实际接收到数据时。

    您可以将调用配置为同步,但这不是推荐的技术。