1

我正在尝试从 jquery 帖子的响应中构建一个数组。我有以下代码:

categories_names = [];
$(categories).each(function(index, category_id) {
    $.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()},
    function(result)
    {
        categories_names.push = result;
    });
}).promise().done(function() {
    var final_cats = categories_names.join("");
    console.info(final_cats);
});

发布请求将类别 ID 插入到表中并返回该类别的名称,格式<li>Category Name here</li>如下加入并作为 html 插入到最终视图中。目前,代码只是在控制台中打印出来,如您所见,但正如您可能已经猜到的那样,它返回(an empty string)

我知道这很可能是一个范围问题,因为这仍然是让我完全困惑的 javascript 领域,所以我希望有人能对此有所了解。

4

2 回答 2

3

.promise().done(...)没有做你认为的那样。它只是立即解决,因为您正在迭代的元素上没有动画。另外,你的语法[].push是错误的。

var defArr = $(categories).map(function(index, category_id) {
    return $.post('/modules/blog/add_post_categories', {post_id:result.result, category_id:$(category_id).val()});
}).get();

$.when.apply(null,defArr).done(function() {
    //var categories_names = [];
    //for (var i = 0; i < arguments.length; i++) {
    //    categories_names.push(arguments[i][0]);
    //}
    var categories_names = $.map(arguments,function(i,arr) {
        return arr[0];
    });
    var final_cats = categories_names.join("");
    console.info(final_cats);
});
于 2013-05-29T17:28:57.030 回答
0
categories_names.push = result;

你能试着把它改成

categories_names.push(result);

因为 push 是一种方法,而不是变量。

于 2013-05-29T17:25:02.247 回答