在Jquery数据表中加载动态数据

时间:2015-07-16 06:48:16

标签: jquery datatables

 var tablerows = '';
var dataSet = [];
if (response.hasOwnProperty('records') && response.metadata.record_count > 0) {
    _.each(response.records, function (record) {
        var sku_data = get_api_data(urls.sku.list + "/" + record.skuid, api.access_token);

        if (sku_data != undefined) {
            sku_data.done(function (sku) {

                dataSet.push(sku.records[0].name);


                console.log(dataSet);
            })



        }

    })


    $('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');

    $('#example').dataTable({
        "data": dataSet,
        "columns": [
            { "title": "Product" }
        ],
        "aoColumns": [
                null
        ]
    });

如何将所有dataSet值动态添加到Datatable。

请立即帮助我得到一个空白阵列。

1 个答案:

答案 0 :(得分:1)

这不是关于jQuery DataTable,您需要使用承诺来解决您的问题

    var tablerows = '';
    var dataSet = [];
    var dataSetPromise = [];
    if (response.hasOwnProperty('records') && response.metadata.record_count > 0) {
        _.each(response.records, function (record) {
            var sku_data = get_api_data(urls.sku.list + "/" + record.skuid, api.access_token);

            if (sku_data != undefined) {
                dataSetPromise.push(sku_data.done(function (sku) {

                    dataSet.push(sku.records[0].name);


                    console.log(dataSet);
                }));



            }

        })

    $.when.apply(null, dataSetPromise).done(function () {
        $('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');

        $('#example').dataTable({
            "data": dataSet,
            "columns": [
                { "title": "Product" }
            ],
            "aoColumns": [
                    null
            ]
        });
});