如何在ajax调用中返回响应

时间:2018-05-28 11:08:01

标签: jquery ajax

如何在ajax调用中返回响应,

我尝试使用以下代码

function getDiscountAmount()
{
    for (var i = 0; i < invoice_ids.length; i++) {
        promises.push(getInvoiceAmountData(amount_tds, invoice_ids[i]));
    }
    Promise.all(promises).then((responses) => {
        var data= responses // need to return the response here
    })
    return data;
    function getInvoiceAmountData(amount_tds, invoice_id) {
        return $.ajax({
            url: "payments/getInvoiceAmount",
            method: "post",
            dataType: 'json',
            data: {"amount_tds": amount_tds, "invoice_id":invoice_id}
        });
    }
 }

现在以不同的功能获得响应

  function getResponse()
  {
      console.log(getDiscountAmount()) //it gives undefined
  }

3 个答案:

答案 0 :(得分:1)

你做得对,只需在正确的地方使用承诺。

function getDiscountAmount()
{
    var promises = [];
    for (var i = 0; i < invoice_ids.length; i++) {
       promises.push(getInvoiceAmountData(amount_tds, invoice_ids[i]));
    }
    Promise.all(promises).then((responses) => {
        var data= responses // need to return the response here
    })
    return data;
}

在ajax函数中使用promise对象

function getInvoiceAmountData(amount_tds, invoice_id) {
    return new Promise(function(resolve, reject){
          $.ajax({
            url: "payments/getInvoiceAmount",
            method: "post",
            dataType: 'json',
            data: {"amount_tds": amount_tds, "invoice_id":invoice_id},
            success: function(data){
                resolve(data);
            },
            error: function(error){
                reject(error);
            });
    });
}

答案 1 :(得分:0)

function getResponse()
  {
    console.log(getDiscountAmount().success(function(data){
         //data is your response
    });
  }

在此处阅读更多内容:jQuery: Return data after ajax call success

答案 2 :(得分:0)

你应该尝试简单的ajax返回功能,但是你是以复杂的方式做到这一点:

试试这个:

function test() {
     myFunction(function(d) {
     console.log(d);
 });
}

function myFunction(callback) {
  var data;
  $.ajax({
    url: 'url',
    data: 'data to send',
    success: function (resp) {
        data = resp;
        callback(data);
    },
    error: function () {}
  });
}