0

我正在使用 html5 和 javascript 创建移动 Web 应用程序。我有两个 javascript 文件。AttributesDatabase.js 和 AttributeView.js.From AttributeView.js 我在执行一个选择查询时从 AttributeDatabase.js 调用一个函数。现在查询结果应该转到 AtttributeView.js。但是 Websql 事务是异步调用,就是这样没有返回正确的结果。有什么方法可以处理 websql 结果。请问有什么办法吗?

已编辑

AttributeView.js

var AttributeDAOObj = new AttributeDAO();

AttributeDAOObj.GetAttributeList();
alert(AttributeDAOObj.GetAttributeList());  //This alert is coming as undefined.   

AttributeDAO.js
this.GetAttributeList = function () {
    var baseDAOObj = new BaseDAO();
    var query = "SELECT AttributeName FROM LOGS";
    //  this.Successcalbackfromsrc = this.myInstance.Successcalback;
    var parm = { 'query': query, 'Successcalback': this.myInstance.Successcalback };
    baseDAOObj.executeSql(parm);
}

//To Create database and execute sql queries.
function BaseDAO() {
this.myInstance = this;
//Creating database
this.GetMobileWebDB = function () {
    if (dbName == null) {
        var dbName = 'ABC';
    }
    var objMobileWebDB = window.openDatabase(dbName, "1.0", dbName, 5 * 1024 * 1024);
    return objMobileWebDB;
}

//Executing queries and getting result 
this.executeSql = function (query) {
    var objMobileWebDB = this.myInstance.GetMobileWebDB();
    objMobileWebDB.transaction(function (transaction) {
 //In this transaction i m returning the result.The result value is coming.
        transaction.executeSql(query, [], function (transaction, result) { return result; }, this.Errorclback);
    });
}

}

4

1 回答 1

0

问题在于您成功回电(如 DCoder 对您问题的评论中所述)

 function (transaction, result) { return result; }

这是返回到哪里?

所以这是如何做到的(或至少一种方式)

例如,您可以这样做:

function (transaction,result){
   console.log("yes, I have some result, but this doesn't say anything, empty result gives also a result");
   // so check if there is a result:
    if (result != null && result.rows != null) {
       if (result.rows.length == 0) {
            // do something if there is no result
       }else{
            for ( var i = 0; i < result.rows.length; i++) {
                var row = result.rows.item(i);
                var id = result.rows.item(i).id; //supposing there is an id in your result
                console.log('Yeah! row id = '+id);
            }
        }
    }else{
       // do something if there is no result
    }
};

请注意,上面的代码可以更紧凑,但这是更好地理解它的方法。

另一种方法是把这个函数放在一段单独的代码中,这样你就可以保持sql语句更加紧凑和可读。就像你叫你错误回调一样,它可以在你的函数中(在它前面有 this.)或一个完全独立的函数。

于 2013-09-13T08:56:08.270 回答