我需要使用$ .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
作为字符串,但函数绝对相等。
如何将函数内联并仍然获得数组结果? 感谢
答案 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');
})
}
});