【问题标题】:aoColumns of datatables are not working properly数据表的 aoColumns 无法正常工作
【发布时间】:2013-08-07 12:52:38
【问题描述】:

我正在尝试处理来自其他 php 页面的 aoColumns 的值。但是它不能正常运行,而如果我使用静态值,那么它就可以正常工作。 我的代码是这样的: 在php页面中

$aoColumn = array("null","null","null","{bSortable: false}");
<input type="hidden" name="aoColumn" id="aoColumn" value="' . implode(",",$aoColumn) . '">

在js页面中

var aos = $('#aoColumn').val();
 var ao = (aos)?aos.split(","):[];
 $.each(ao,function(i){
 });

并在 dataTable 声明中: "aoColumns":ao

但它不起作用。 请让我知道这个问题。 提前致谢。

更新

我知道,在我的情况下,aoColumns 打印 ["null", "null", "null", "{bSortable: false}"] 而它应该是 [null,null,null,Object{bSortable=false}]。怎么做?

【问题讨论】:

    标签: php jquery sorting datatables


    【解决方案1】:

    $aoColumn 传递给脚本的方式是错误的。你应该将它作为 JSON 传递——如果 JSON 在 HTML 中传输,它也需要正确地进行 HTML 编码:

    $aoColumn = array(null, null, null, array('bSortable' => false));
    echo '<input ... value="' . htmlspecialchars(json_encode($aoColumn)).'">';
    

    然后用$.parseJSON把它变回一个对象:

    var aoColumn = $.parseJSON($('#aoColumn').val());
    

    但是,我完全不确定您为什么要打扰隐藏字段。您可以直接将配置传递给 JavaScript:

    <?php $aoColumn = array(null, null, null, array('bSortable' => false)); ?>
    
    <!-- later on.... -->
    <script>
        var aoColumn = <?php echo json_encode($aoColumn); ?>;
    </script>
    

    【讨论】:

    • 很好的答案,但这不是完全不同的方法吗?如果 Mausumi 不能/不允许更改 PHP 脚本怎么办?
    • @davidkonrad:那么他们应该说有特定的限制。虽然我怀疑是这样,因为问题是“我的代码就像......”。
    • 是的,但正如你所看到的 - 有时我们想要的只是一个答案,而不是一个讲座
    • @davidkonrad:每个人都有自己的 :-)
    【解决方案2】:

    这是一个有趣的 :-) 以 1:1 的比例进行设置(尽管只有 3 列):

    <?
    $aoColumn = array("null", "{bSortable: false}", "null");
    echo '<input type="hidden" name="aoColumn" id="aoColumn" value="' . implode(",",$aoColumn) . '">';
    ?>
    

    JS

    var ao = [];
    var aos = $('#aoColumn').val().split(',');
    for (var i=0;i<aos.length;i++) {
        if (aos[i]=='null') {
            //no need for processing
            ao.push('{ null }');
        } else {
            //remove {, } and whitespace, return array splitted by :
            var s = aos[i].replace('{','').replace('}','').replace(' ','').split(':');
            //create object
            var o = {};
            //here you need to force a real boolean instead of "false"
            o[s[0].toString()]=(s[1]=="false") ? false : true;
            ao.push(o);
        }
    }
    
    $('#table').dataTable({
        "aoColumns": ao
    });
    

    维奥拉。 Datatables 解析 ao 正确,第二列不可排序。

    【讨论】:

    • 非常感谢大卫康拉德。实际上我想为 aoColumns 设置一个动态值。现在它按我的预期正常工作。再次非常感谢。
    【解决方案3】:
    JSON.parse('[null, null, null, {"bSortable": false}]');
    

    修改你的内爆函数,使你的value="[null, null, null, {\"bSortable\": false}]" 然后在.val() 上运行JSON.parse() 以获取您的设置对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多