Knockout JS和DataTables Ajax和PHP

时间:2015-02-27 22:36:41

标签: php jquery ajax knockout.js datatables

function Lead(data){
    this.id = data.id;
    this.name = ko.observable(data.name);
    this.number = ko.observable(data.mobile);
    this.email = ko.observable(data.email);
    this.return_date = ko.observable(data.return_date);
    this.advert = ko.observable(data.advert);
    this.date_enquired = ko.observable(data.date);

}

function leadView(){
   var self = this;
   
   self.leads = ko.observableArray([]);
   
    $.getJSON('ajax/leads.php', function(data){
            
            var mapped = $.map(data, function(info){
                return new Lead(info);
            });
            
            self.leads(mapped);
            
            var dt = $('#lead-table').DataTable({
                        dom: "tip",
                        ordering: false,
                        bProcessing: true,
                        data: self.leads(),
                        columns: [
                            {data: 'name()' },
                            {data: 'number()' },
                            {data: 'email()' },
                            {data: 'return_date()' },
                            {data: 'advert()' },
                            {data: 'date_enquired()' }
                        ]
                    });
        });

    self.update = function(){
        $.getJSON('leads.php', function(data){
            
            var mapped = $.map(data, function(info){
                return new Lead(info);
            });
            
            self.leads(mapped);
        });
     
    }
    
}

var DataLeadView = new leadView();

window.setInterval(DataLeadView.update, 5000);
ko.applyBindings(DataLeadView);

我有这个代码,使用Knockout JS和DataTables打印出我的表,我有一个显示潜在客户总数的计数器。

然后我运行我的函数来更新lead()observableArray; 更新计数器但不更新表 所以我的问题是如何让表格添加刚刚添加到数组中的行?

1 个答案:

答案 0 :(得分:1)

您只需使用draw重绘表格以显示更新后的更改

代码:

self.update = function () {

            var mapped = $.map(data, function (info) {
                return new Lead(info);
            });

            self.leads(mapped);
            dt.clear(); // clear table
            dt.rows.add(self.leads()); // build the source again by adding
            dt.draw() ; // draw table with added rows
        }

工作小提琴 here