【问题标题】:need to get value from ajax [duplicate]需要从ajax中获取价值[重复]
【发布时间】:2023-04-04 00:36:01
【问题描述】:

我在文档就绪函数上调用 getValues 函数。

jQuery(document).ready(function () {

        getValues();

    });

getValues 函数如下所示。它正在调用 getOffValue 函数。

var getValues= function() {
    var html = '';

    jQuery.ajax({
        url: 'controller/function',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            jQuery.each(data, function (index, element) {
              rate=getOffValue(element.off_id);

                        html += '<div class="col-md-3" style="padding:10px"><div class="row"></div></div>';


            });
            jQuery("#div").append(html);




        },
        error: function (data) {
            alert("Error" + data);
        }

    });

}

getOffValue 函数如下所示。需要将其结果返回给调用函数。

var getOffValue = function(id) {
    var html = '';

   return jQuery.ajax({
        url: 'controller/function1',
        type: 'POST',
        dataType: 'json',
        data: {off_id:id},
        success: function (data) {
            return data[0].rate;
            },
        error: function (data) {
            alert("Error" + data);
        }

    });

}

我需要将getOffValue函数的成功结果返回给函数getOffValue。需要在速率变量中获取该值。并且需要在 html 中附加该值。但是此代码不起作用。将值显示为未定义。提前感谢

【问题讨论】:

  • Ajax 是异步调用,因此您必须使用 Promises/Observables 来实现此功能

标签: jquery ajax codeigniter


【解决方案1】:

您可以尝试使用Promises。此代码未经测试且未优化,但应解释该概念。

function getOffValue(id) {
    var deferred = jQuery.Deferred();
    jQuery.ajax({
        url: 'controller/function1',
        type: 'POST',
        dataType: 'json',
        data: {off_id:id},
        success: function (data) {
            return deferred.resolve(data[0].rate);
        },
        error: function (data) {
            alert("Error" + data);
            return deferred.reject(data);
        }

    });
    return deferred.promise();
}

var getValues= function() {
    var html;
    jQuery.ajax({
        url: 'controller/function',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            jQuery.each(data, function (index, element) {
                getOffValue(element.off_id).then(function(rate) {
                    console.log('rate', rate); //you need to append it to the html
                    html = '<div class="col-md-3" style="padding:10px"><div class="row"></div></div>';
                    jQuery("#div").append(html);
                });
            });
        },
        error: function (data) {
            alert("Error" + data);
        }
    });
}

请记住,您正在对 controller/function1 进行多次 ajax 调用 - 为了提高性能,您可能应该对其进行优化,以便 function1 返回一个速率数组。

【讨论】:

  • 这是一个不同的问题,但理论上你可以用值做任何你想做的事情,例如html = "&lt;div&gt;"+rate+"&lt;/div&gt;"。如果回答了您原来的问题,请标记为已解决。
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 2012-09-19
  • 1970-01-01
  • 2017-10-19
  • 2016-01-26
  • 2019-03-25
  • 1970-01-01
相关资源
最近更新 更多