$内部的函数结果数组.Ajax被转换为字符串

Function result array inside $.ajax is converted to string

本文关键字:转换 字符串 Ajax 数组 内部 函数 结果      更新时间:2023-09-26

我需要传递id数组与$。Ajax数据变量。该数组是函数的结果。如果我在 $之外声明这个函数。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;
        }
    }
});

Here's fiddle: http://jsfiddle.net/vxLrN/7/

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

我怎么能把函数内联,仍然得到数组结果?由于

请确保调用这个匿名函数,以便将正确的结果(字符串数组)分配给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
}

直接使用$。映射直接构建数组

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