2014-09-05 23 views
0

This post answered the question I was about to ask。唯一的问题是我需要使用第一个调用的结果作为第二个Ajax调用的参数。jquery Ajax:如何使用第一个ajax的结果调用第二个调用? (.then(function()))

事实上,我需要为某个客户获得联系。但是,我唯一的论点是来自该客户的请求。我想先打电话来获取客户端的客户端号码,然后使用该ID来查询所有联系人。

有人可以提供一个小代码其中第一个查询的结果是用来进行第二次调用吗?

这里是他写的部分代码。

$.ajax({..}) // Promise 1 
.then(function() { 
    // This will only fire if the first request had no error - was "done" 
    // We then return a NEW promise for the 2nd request. In a proper 
    // Promises/A, 'then' returns a (new) promise. 
    return $.ajax({..}) // Promise 2 
}) 

感谢您的帮助。

+2

呃... ...这是在传递给你。然后回调的第一个参数... – 2014-09-05 20:30:34

+0

@KevinB,我不是太阿贾克斯familliar。我刚刚在第一个电话里面打了另一个电话,但我认为这应该是最好的方式。你能提供一个样本,我该怎么做? – Richard77 2014-09-05 20:32:50

回答

0

.then回调包含承诺的结果。在这种情况下,它将包含三个参数,与传递给$.ajax成功回调的相同三个参数:解析结果,文本状态和jqXHR对象。

$.ajax({..}) // Promise 1 
.then(function (result, status, jqXHR) { 
    // This will only fire if the first request had no error - was "done" 
    // We then return a NEW promise for the 2nd request. In a proper 
    // Promises/A, 'then' returns a (new) promise. 
    console.log(result); 
    return $.ajax({..}) // Promise 2 
}).done(function (contacts, status, jqXHR) { 
    //... 
}); 

您可以使用result从响应中获取客户ID。最后的.done将被第二个承诺的响应触发。

+0

.then函数中的结果是否与第一个ajax调用返回的结果相同? – Richard77 2014-09-05 20:42:41

+0

是的,它是一样的。 – 2014-09-05 20:48:18

0

会这样的工作吗?

function getContacts(data){ 
    $.ajax({ 
     type: 'POST', 
     dataType: dataType, 
     url: 'someotherUrl', 
     data: idofclient = data.idofclient 
     success: function(data){ 
      console.log(data.contact); 
     } 
    }); 
} 

$.ajax({ 
    type: 'POST', 
    dataType: dataType, 
    url: 'someUrl', 
    success: function(data){ 
     getContacts(data); //data should have the id of the client of course 
    } 
}); 
+0

我想这应该可行,但我认为这并不像我使用过的那样简洁。然而,我认为它应该没问题。 – Richard77 2014-09-05 20:41:24

+0

啊,我不知何故错过了.then(函数() - 你的问题的一部分。) – aolsen 2014-09-05 20:45:35

1
$.ajax({...}).then(function (d1) { 
    // d1 is the data returned from the first ajax call. 
    // You can use it as a parameter to the second ajax call below. 
    return $.ajax({...}).done(function (d2) { 
     // d2 is the data returned from the second ajax call. 
     console.log(d1, d2); 
    }) 
}); 
+0

这更像它。我正在尝试它。 – Richard77 2014-09-05 20:44:38

相关问题