简体   繁体   English

使用.done的嵌套AJAX调用

[英]Nested AJAX Calls using .done

I'm fairly new to AJAX, but working on a project that requires an ajax call to validate a specific value, then make another ajax call if the first returns the expected value. 我对AJAX还是很陌生,但正在从事一个需要ajax调用来验证特定值的项目,然后如果第一个返回期望值,则再进行一次ajax调用。 I am trying to implement the .done/.fail model, but can't find a way to prevent both calls from happening simultaneously, rather than once the first call is done and successful. 我正在尝试实现.done / .fail模型,但是找不到阻止两个调用同时发生的方法,而不是一旦第一个调用完成并成功就阻止了这两种方法。

The following code will call the ajaxCall function twice, but concurrently rather than consecutively. 以下代码将两次调用ajaxCall函数,但同时调用而不是连续调用。 I have researched a ton of code, including Nested AJAX Calls , jQuery getting rid of nested ajax functions , and $.when.done callback isn't working , but none seem to fit my exact scenario, or maybe I just don't understand the code. 我研究了很多代码,包括嵌套的AJAX调用jQuery摆脱了嵌套的Ajax函数以及$ .when.done回调不起作用 ,但似乎没有一个适合我的实际情况,或者也许我只是不明白编码。 Either way, I haven't been able to find a solution, and any help will be much appreciated! 无论哪种方式,我都无法找到解决方案,我们将不胜感激!

var xReturn = ajaxCall("1");    

xReturn.done(function(msg){
    console.log("callback "+msg+" successful");

    // if successful, place second call
    if(parseInt(msg)==1)
        xReturn = ajaxCall("2");    
});


function ajaxCall(mop){
    return $.ajax({
         url: "getItem.php",
         type: "POST",
         data: {code: '<?php echo $code; ?> ', op:mop}
    });
}

It seems like promises may be the way to go, but I can't wrap my head around how to use them in this scenario. 似乎可以兑现诺言 ,但我无法确定在这种情况下如何使用诺言 Thanks in advance for any pointers in the right direction. 在此先感谢您指出正确方向的任何指针。

Update: 更新:

I ran through a battery of tests with different results. 我进行了一系列测试,结果各不相同。 For my final test last night, I placed another console.log(msg); 为了进行昨晚的最终测试,我放置了另一个console.log(msg); directly after ajaxCall("2"); 直接在ajaxCall("2"); Each time the resulting msg was always "1", leading me to believe the calls were not happening properly. 每次生成的味精始终为“ 1”时,使我相信呼叫未正确进行。 This result tells me that xReturn.done(function(msg)... is only being called once, but I thought it would be called with each ajax call. 这个结果告诉我xReturn.done(function(msg)...仅被调用一次,但是我认为每次ajax调用都将调用它。

With this new information, I will perform additional testing tonight and report back. 有了这些新信息,我将在今晚进行其他测试并向您报告。
Thanks 谢谢

You need to bind a .done() method to each promise. 您需要将.done()方法绑定到每个 Promise。 xReturn.done() binds a function to that promise. xReturn.done()将函数绑定到该xReturn.done()

When you do xReturn = ajaxCall("2"); 当您执行xReturn = ajaxCall("2"); , you are replacing xReturn with a different object. ,您 xReturn 替换为其他对象。 This object does not have a .done() method bound to it. 此对象没有绑定到.done()方法。

You need to bind .done() to each promise, that doesn't happen automatically. 您需要将.done()绑定到每个promise,但这不会自动发生。

var xReturn = ajaxCall("1");
// This binds the callback to this *specific* promise    
xReturn.done(ajaxDone);    

function ajaxCall(mop){
    return $.ajax({
         url: "getItem.php",
         type: "POST",
         data: {code: '<?php echo $code; ?> ', op:mop}
    });
}

function ajaxDone(msg){
    console.log("callback "+msg+" successful");

    // if successful, place second call
    if(parseInt(msg)==1){
        xReturn = ajaxCall("2");

        // Bind a callback to this *new* object
        xReturn.done(ajaxDone);
    }
}

There are multiple ways to go about this problem. 有多种方法可以解决此问题。

You could simply call the second ajax call from the success of the first. 您可以从第一个成功调用第二个ajax调用。 Something on the following lines 以下几行内容

function ajaxCall(mop){
    $.ajax({
         url: "getItem.php",
         type: "POST",
         data: {code: '<?php echo $code; ?> ', op:mop}
    }).done(function(msg) {
        console.log("First call is done. Received data as ", msg);
        if(parseInt(msg)==1) {
            $.ajax({
                //Repeat Options
            }).done(function(newMsg)) {
                console.log("We're done");
            };
        }
    });
}

} }

If you do want to use the .done/.fail model, you could try using $.when . 如果确实要使用.done / .fail模型,则可以尝试使用$.when Here is a working fiddle that does consecutive calls using the same function. 这是一个工作小提琴 ,使用相同的功能进行连续的调用。

function ajaxCall(mop){
    return $.ajax({
            url: "/echo/json/",
            type: "POST",
            data: {
                json: $.toJSON({data: mop}),
                delay: Math.floor(Math.random()*4)
            }
    });
}

$.when(ajaxCall("1")).done(function(data) {
    console.log("Done with first call. About to call second");
        if(data /* and add whatever conditions you need to call the next function */) {
            ajaxCall("2");
        }
});

Try it like this. 这样尝试。

ajaxCall("1"); 

function ajaxCall(mop){
$.post( "getItem.php", {code: '<?php echo $code; ?> ', op:mop})
  .done(function( msg) {
    console.log("callback "+msg+" successful");
    if(parseInt(msg)==1)
        ajaxCall("2"); 
  });

}

And also you can use these with previous code 您也可以将它们与以前的代码一起使用

  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );

How about that: 那个怎么样:

var xReturn1 = ajaxCall("1"),
    xReturn2 = ajaxCall("2");

$.when(xReturn1, xReturn2).done(function( a1, a2 ) {
    var data1 = a1[0], data2 = a2[0];
    console.log("Both done");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM