Jquery Ajax:如何使用第一个ajax调用的结果进行第二次调用? (。然后(函数()))

时间:2014-09-05 20:29:06

标签: jquery ajax

post answered the question I was about to ask。唯一的问题是我需要使用第一个调用的结果作为第二个ajax调用的参数。

事实上,我需要为某个客户获取联系人。但是,我唯一的参数是来自该客户端的请求。我想第一次打电话来获取客户端的客户端号码,然后使用该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
})

感谢帮助。

3 个答案:

答案 0 :(得分: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);
    })
});

答案 1 :(得分:0)

.then callback(s)包含来自其承诺的结果。在这种情况下,它将包含三个参数,相同的三个参数传递给$.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将由第二个承诺的响应触发。

答案 2 :(得分: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
    }
});
相关问题