2014-03-29 98 views
0

我需要傳遞帶有$ .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字符串,雖然功能是絕對平等的。

我怎樣才能把函數內聯,仍然得到數組結果? 感謝

+3

真的嗎?您沒有執行該功能,而是將其作爲數據發送。 – adeneo

+1

將它包裹在IIFE中 – lshettyl

回答

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 
} 
+0

太棒了!謝謝,這解決了這個問題。 – Alex

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'); 
       }) 
    } 
}); 
+0

這是更少的代碼。雖然,我接受Darin的答覆,因爲它更接近這個話題,但我想我會用你的解決方案。謝謝 – Alex