2013-04-22 55 views
0

我正在处理一个巨大的自定义数据表函数,我有一个简单的问题,我需要将'sType'设置为所有'aoColumns',但这些表是动态的,所以他们可能有6或10列,我不能找到一个办法的事,我已经尝试以下选项:将sType设置为动态jQuery数据表上的所有aColumns

//doesn't work 
"aoColumns": [{"sType":"string", "aTargets": ["_all"]}], 

//this works, but its not dynamic :/ 
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}], 

,我不能做到这一点使用服务器端

obs .:我有一个var列数

6 columns 
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}], 
10 columns 
"aoColumns": [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}, {"sType":"string"}], 

还是要谢谢你

+0

你最初建表在PHP? – dgig 2013-04-22 20:38:43

+0

是的,但只有thead和搜索输入,使用ajax加载数据 – 2013-04-22 20:39:46

+0

在设置数据表值之前,计算您将使用php的列,然后使用while循环创建许多“{”sType“:”字符串“}”,如你所需。那有意义吗? – dgig 2013-04-22 20:43:37

回答

1

服务器端PHP:嗯,如果你是PHP创建表,那么你应该能够建立一个字符串,所有可以插入javacript所需的组的部分。

<?php 
$colnum = 6; 
$i = 1; 

$aocolumns = array(); 

while($i <= $colnum){ 
    $aocolumns[] = '{"sType":"string"}'; 
    $i++; 
} 

$aocolumns = join(",",$aocolumns); 
$aocolumns = '[' . $aocolumns . ']'; 

?> 

然后把它像

"aoColumns": <?=$aocolumns?> 

的Javascript:假设你得到的列从阿贾克斯称为“COLS”一个数组回来了,你可以试试这个for循环。 :

var aocolumns = []; 
for(i in cols){ 
    var ao = {"sType":"string"}; 
    aocolumns.push(ao); 
} 
alert(aocolumns); 
+0

返回空白.. – 2013-04-22 20:57:24

+0

对不起,我做了一个编辑。你能提供ajax调用返回的字符串吗? – dgig 2013-04-22 20:58:24

+0

对不起,只有行是由ajax获得,列是固定的,但它可以根据不同的表,看看这个问题,我做了一个编辑 – 2013-04-22 21:01:27

0

我解决了这个利用parseJSON和将字符串转换成JSON:

aoColumns = '[{"sType":"string"}'; 
i = 0; 
tc = totalCol; 
while(i<tc){ 
    aoColumns += ','; 
    aoColumns += '{"sType":"string"}'; 
    i++; 
} 
aoColumns += ']'; 

// if totalCol == 3 then 
// aoColumns will return [{"sType":"string"}, {"sType":"string"}, {"sType":"string"}] 
aoColumns = $.parseJSON(aoColumns); 

这个工作!

1

其他答案比他们需要更复杂。

的JavaScript版本:

var i, aoColumns = []; 
for (i = 0; i < totalCol; i++) { 
    aoColumns.push({ 'sType': 'string' }); 
} 

的ECMAScript 6版本:

aoColumns.fill({ 'sType': 'string' }, 0, totalCol) 

这可能会在你的浏览器中运行,如果填充工具存在于你使用任何图书馆的JavaScript array.fill命令。

PHP(服务器端)版本:

<?php 
// array('stype' => "string"); for old PHP 
$columns = 6; 
$aoColumns = array_fill(0, $columns, [ 'stype' => 'string' ]); 
print json_encode($aoColumns); 
?> 
+0

真棒,今天我学到了一些新东西! :D – 2014-07-10 15:01:02

+0

在几周的时间里,你可以通过类似'aoColumns.fill({'sType':'string'},0,totalCol)'来初始化。 (即将在ECMAScript 6中发布) – vogomatix 2014-07-10 15:15:32

+1

已添加PHP版本:) – vogomatix 2015-12-09 14:50:25