【问题标题】:Function result array inside $.ajax is converted to string$.ajax 中的函数结果数组转换为字符串
【发布时间】:2014-03-29 09:44:51
【问题描述】:

我需要使用 $.ajax 数据变量传递 id 数组。数组是函数的结果。如果我在 outside $.ajax 声明此函数,它会正确发送数组。但是,如果我将相同的功能代码 inside $.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 作为字符串发送,不过,函数是绝对相等的。

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

【问题讨论】:

  • 真的吗?您不是在执行该函数,而是将其作为数据发送。

标签: javascript jquery ajax arrays


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    直接使用 $.map 构建数组即可

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

    【讨论】:

    • 这是更少的代码。虽然,我接受了达林的回复,因为它更接近主题,但我想我会使用你的解决方案。谢谢
    猜你喜欢
    • 2013-04-12
    • 2010-12-13
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多