2014-03-29 42 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