Jquery在executeSQL之前等待返回JSON对象

时间:2016-12-12 16:04:43

标签: javascript jquery json ajax web-sql

在以下函数中,如何在继续执行sql事务之前告诉JS等待返回我的ajax调用。 以下示例代码当前正确获取数据,但是在AJAX调用填充employees []之前执行sql事务

我尝试在成功后放置sql操作但是我收到了以下错误

Uncaught DOMException: Failed to execute 'executeSql' on 'SQLTransaction': SQL execution is disallowed.

以下是代码的一部分

var addSampleData = function (tx, employees) {

        var employees = [];

$.ajax({
            url: 'my-path-to-my-json-answer',
            success: function (value, status) {
            employees.push(value);
        },
        error: function (XMLHttpRequest, textStatus, exception) {
            console.log("Connection with the server fail.\n" + textStatus + 'status is: ' + exception);
        }
    });

        var l = employees.length;

        var sql = "INSERT OR REPLACE INTO leaderboard " +
        "(id, uFname, uLname, uRegion, uCountry, uScore) " +
        "VALUES (?,?,?,?,?,?)";

        var e;

        for (var i = 0; i < l; i = i + 1) {
            e = employees[i];
            tx.executeSql(sql, [e.id, e.uFname, e.uLname, e.uRegion, e.uCountry, e.uScore],
                function () {
                    console.log('INSERT success');
                },
                function (tx, error) {
                    console.log('INSERT error: ' + error.message);
                });
        }   

    }

欢迎任何改进该代码的建议。

1 个答案:

答案 0 :(得分:0)

这是因为Ajax调用是异步的,浏览器为ajax调用启动一个单独的线程。为了在ajax调用完成后执行你的SQL查询,把你想要的代码放到ajax的成功方法中的SQL查询代码中,如下所示......

jQuery.ajax({
        type:"post",
        dataType:"json",
        url: myAjax.ajaxurl,
        data: {action: 'submit_data', info: info},
        success: function(data) {
            //do your SQL work here...
            console.log('doing SQL work');
        },
        error: function(data) {
           console.log('boo...boo...');
        },
    });