我有一个索引页面,在转到另一个页面之前,我想使用它来建立本地数据库。但是,每当我激活window.location代码时,其他功能都不会运行,但是当我注释掉时,其他功能都可以正常运行。有什么想法会导致这种情况,以及如何使功能和window.locations正常工作?代码如下:

<script>
        var db = window.openDatabase("DB1", "", "DB", 1024 * 1000)
            CreateDB(); //Creates local database tables
            loadRouteList(); //Queries web server database using AJAX and inserts Routes
            window.location = 'Application.html';
</script>


使用的功能:

function CreateDB() {
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Routes(id INTEGER PRIMARY KEY, routeID TEXT, customerID TEXT, stopSeq TEXT, driverID TEXT)', []);
    });
};
function loadRouteList() {
var dataObject = {
    postDesignator: 'routes',
};
$.ajax({
    url: 'http://url.php',
    data: dataObject,
    dataType: 'json',
    type: 'post',
    success: function (Result) {
        for (var i = 0, len = Result.records.length; i < len; ++i) {
            var route = Result.records[i].record;
            insertRoute(route.routeID, null, null, null);
        }
    }
});
}

最佳答案

根据定义,AJAX是Asynchronous,因此,如果您运行这些功能并且不等待它们完成,则代码将继续运行而无需等待它们。因此,您到达的位置因线路而异。您必须等到所有请求都完成后才能继续,要执行此操作,您必须更改函数中的代码。如果您发布它们,我们可以为您提供帮助。

编辑

我认为,最好的方法是将回调传递给函数:

function CreateDB() {
    db.transaction(function (tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS Routes(id INTEGER PRIMARY KEY, routeID TEXT, customerID TEXT, stopSeq TEXT, driverID TEXT)', []);
    });
    //if even this piece of code is async you should read docs and check how to call a function after the query executed
};
function loadRouteList(callback) {
    var dataObject = {
        postDesignator: 'routes',
    };
    $.ajax({
        url: 'http://url.php',
        data: dataObject,
        dataType: 'json',
        type: 'post',
        success: function (Result) {
            for (var i = 0, len = Result.records.length; i < len; ++i) {
                var route = Result.records[i].record;
                insertRoute(route.routeID, null, null, null);
            }
            if(callback) {
                callback();
            }
        }
    });
}


然后以这种方式使用它:

var db = window.openDatabase("DB1", "", "DB", 1024 * 1000)
    CreateDB(); //Creates local database tables
    loadRouteList(function() {
        window.location = 'Application.html';
    });

关于javascript - 延迟window.location以留出时间进行AJAX,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16678983/

10-12 12:35
查看更多