需要从ajax获得价值

时间:2017-12-13 17:47:35

标签: jquery ajax codeigniter

我在文档就绪函数上调用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。需要在rate变量中获取该值。并且需要在html中附加该值。但是此代码不起作用。将值显示为undefined.thanks提前

1 个答案:

答案 0 :(得分:-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返回一组速率。

相关问题