带数据的Init表仅适用于断点

时间:2015-01-05 16:31:10

标签: javascript jquery ajax twitter-bootstrap

我使用ajax获取的数据初始化表(使用此lib bootstrap-table)。

var arr = [];
        var getRows = function () {
            $.ajax({
                type: "GET",
                url: hostUrl,
                contentType: "application/json;",
                dataType: "json",
                success: function (result) {
                    arr = result.d;
                }
            });
            return arr; // breakpoint here
        };

$('#bootstrap-table').bootstrapTable({
            data: getRows()
});

此代码仅在我在getRows函数中返回时设置断点时才有效。尝试在返回前添加超时 - 但这没有帮助。

如果我不添加breakPoint,我什么也得不到。

3 个答案:

答案 0 :(得分:1)

ajax调用是异步的。

在呼叫返回之前返回arr。

你最好选择这样的东西:

        $.ajax({
            type: "GET",
            url: hostUrl,
            contentType: "application/json;",
            dataType: "json",
            success: function (result) {
                $('#bootstrap-table').bootstrapTable({
                 data: result.d
                });
            }
        });

答案 1 :(得分:1)

您缺少查询中的async参数

$.ajax({
            type: "GET",
            url: hostUrl,
            async: false, //This is the guy you want !!!!!!!!!!!!!
            contentType: "application/json;",
            dataType: "json",
            success: function (result) {
                arr = result.d;
            }
        });

答案 2 :(得分:0)

你实际上最好使用承诺。只需返回$.ajax承诺并处理该函数外部返回的数据:

// GetRows promises to return rows of data...
var getRows = function () {

    // simply return the ajax promise
    return $.ajax({
        type: "GET",
        url: hostUrl,
        contentType: "application/json;",
        dataType: "json",
    });
};

像这样消费:

// Use the returned promise to process the data
getRows().done(function(rows){
    $('#bootstrap-table').bootstrapTable({
        data: rows
    });
});

回调或success:处理程序的问题是您正在构建GetRows方法的GUI依赖项。

相关问题