我需要传递带有$ .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
字符串,虽然功能是绝对平等的。
我怎样才能把函数内联,仍然得到数组结果? 感谢
真的吗?您没有执行该功能,而是将其作为数据发送。 – adeneo
将它包裹在IIFE中 – lshettyl