$ .ajax中的函数结果数组转换为字符串

时间:2014-03-29 09:44:51

标签: javascript jquery ajax arrays

我需要使用$ .ajax数据变量传递id数组。该数组是函数的结果。如果我声明此功能 $ .ajax之外,它会正确发送数组。但是如果我把相同的功能代码放在 $ .ajax(这是我的优先选择)中,我会把它作为一个字符串。

function mySort(){ // Do not pass hidden clones
    var items = [];
    $('#fp_parameters_list').children().each(function(){
        if ($(this).is(':visible')) {         
            items.push($(this).attr('data-parameter-id'));
        }
    });
    return items;
}

// This gives correct ordering
$.ajax({
    url: '/echo/json/',
    type: 'post',
    dataType: 'json',
    data: {
        ordering: mySort()
    }
});


// This gives ordering as a string
$.ajax({
    url: '/echo/json/',
    type: 'post',
    dataType: 'json',
    data: {
        ordering: function(){ // Do not pass hidden clones
            var items = [];
            $('#fp_parameters_list').children().each(function(){
                if ($(this).is(':visible')) {         
                    items.push($(this).attr('data-parameter-id'));
                }
            });
            return items;
        }
    }
});

这里的小提琴:http://jsfiddle.net/vxLrN/7/

您可以看到第一个请求是以ordering作为数组发送的,而第二个传递ordering作为字符串,但函数绝对相等。

如何将函数内联并仍然获得数组结果? 感谢

2 个答案:

答案 0 :(得分:4)

确保调用此匿名函数,以便为ordering参数指定正确的结果(字符串数组):

data: {
    ordering: (function () { // Do not pass hidden clones
        var items = [];
        $('#fp_parameters_list').children().each(function() {
            if ($(this).is(':visible')) {
                 items.push($(this).attr('data-parameter-id'));
             }
         });
         return items;
    })(); // <!-- Here call the anonymous function to get its result
}

答案 1 :(得分:1)

只需使用$ .map直接构建数组

$.ajax({
  url: '/echo/json/',
  type: 'post',
  dataType: 'json',
  data: {
    ordering: $.map($('#fp_parameters_list').children(':visible'), function(el) {
                 return $(el).data('parameter-id');
              })
  }
});