【问题标题】:Fill array through ajax request通过ajax请求填充数组
【发布时间】:2015-08-16 03:44:54
【问题描述】:

我需要通过 AJAX 从数据库中收集一些数据并将其放入一个数组中。很遗憾,由于某种原因,我无法存档。

AJAX 发送数据以检索特定数据。该数据如下:

[{"comment_id":154,"comment_text":"Moduleboeken PHP","date_updated":"2015-06-01 10:34:47"},{"comment_id":155,"comment_text":"Moduleboeken JAVA","date_updated":"2015-06-01 10:34:54"}]
[{"comment_id":149,"comment_text":"Werksfeer","date_updated":"2015-06-01 10:33:57"}]
[{"comment_id":152,"comment_text":"Begeleiding Elleke Jagersma","date_updated":"2015-06-01 10:34:27"}]
[{"comment_id":260,"comment_text":"Studievoortgang JAVA","date_updated":"2015-06-01 13:01:15"}]
[{"comment_id":153,"comment_text":"Faciliteiten","date_updated":"2015-06-01 10:34:39"}]

收集这些数据的函数:

function sendRetrieveAjax(url, data) {
    return new Promise(function(resolve, reject) {
        $.ajax({
            url: url, type: 'post', data: data,                
            success: function(data) {
                resolve(data);
            },
            error: function(request, status, error) {
                reject([{request: request, status: status, error: error}]);
            }
        });
    });
}

主代码运行 5 个 DOM 元素,从它们中收集一个 ID,并在 AJAX 发送和检索函数中使用它。如果这成功了,它将把它放在一个数组中。

var elements = $('.note_block');
var dataCollection = new Array();

for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
        console.log(data);
        dataCollection[i] = data;
    });
}
console.log(dataCollection);

不幸的是数组是空的,而控制台显示正确的数据。

谁能启发我?

【问题讨论】:

  • 仅供参考,jQuery.post 返回一个实现它自己的对象Promise interface
  • @RGraham,不知道,但现在知道了,谢谢!
  • @dfsq,那篇文章帮助我实现了我的 ajax 调用的 promise 方法。但这并不能解决我的问题。
  • 您的问题是您试图在then 块中填充dataCollection,但在外部填充console.log(dataCollection)。然而 dataCollection 到那时还没有填充。
  • @Smooth,请看下面的答案

标签: javascript jquery ajax promise


【解决方案1】:

你有两个问题

  1. 您需要将i 的值绑定到sendRetrieveAjax
  2. dataCollection的值填写后需要打印出来(注意promise的使用)

要解决第一个问题,您需要使用IIFE(立即调用函数表达式)

for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    (function(_i) {
        sendRetrieveAjax('../functions/getcomments.php', data).then(function(data) {
            console.log(data);
            dataCollection[_i] = data;
        });
    })(i);
}

而要解决第二个问题,您可以使用数组或 promise 将所有请求的 promise 保存在其中,并按顺序或并行执行它们

var requests = []
;

for(i = 0; i < elements.length; i++) {
    var element = $(elements[i]);
    var data = {
        commenttype_id  :   element.children('#commenttype_id').val(),
        week_id         :   $('#week_id').val()
    }

    // No need to store the URL, just store the data
    requests.push(data);
}

requests = requests.map(function(data) {
    return sendRetrieveAjax('../functions/getcomments.php', data);
});

Promise.all(requests).done(function(responses) {
    console.log(responses);
    dataCollection = responses;
}, function(err) {
});

【讨论】:

    【解决方案2】:

    您需要将每个单独的响应映射到正确的数组索引。在这种情况下,最佳解决方案是使用$.when 提供一组承诺,并使用有序响应数据对象获取集中式响应对象。

    我还将sendRetrieveAjax 简化为$.ajax 已经返回promise 对象:

    function sendRetrieveAjax(url, data) {
        return $.ajax({
            url: url,
            type: 'post',
            data: data
        });
    }
    
    var promises = $('.note_block').map(function(i) {
        return sendRetrieveAjax('../functions/getcomments.php', {
            commenttype_id: $(this).children('.commenttype_id').val(),
            week_id: $('#week_id').val()
        });
    }).get();
    
    $.when.apply(null, promises).then(function() {
        var dataCollection = $.map(arguments, function(data) {
            return data[0];
        });
        console.log('Data Collection', dataCollection);
    });
    

    还有一点,不要重复 id,改用 .commenttype_id 类。

    这是一个演示:http://plnkr.co/edit/r9NnlxIQjUhNvTYwfLy7?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2011-03-18
      • 1970-01-01
      相关资源
      最近更新 更多