我需要傳遞帶有$ .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