javascript 如何在事务回调函数中传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8775955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can I pass argument in transaction callback function
提问by cjmling
From a tutorial code like this
从这样的教程代码
function queryDB(tx) {
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
in db.transaction i want to pass a variable as argument to queryDB function, so the code which i think of should looks like
在 db.transaction 我想将一个变量作为参数传递给 queryDB 函数,所以我想到的代码应该看起来像
db.transaction(queryDB(id), errorCB);
How I can actually implement this ? Or its simply gonna work like this and my id will be passed and get in tx ?
我如何才能真正实现这一点?或者它只是像这样工作,我的 id 将被传递并进入 tx ?
回答by JohnP
Wrap it in a function again
再次将其包裹在一个函数中
var id = 'THEID';
db.transaction(function(){
queryDB(id)
}, errorCB);
Note - This is assuming that you're making the API. Some APIs / frameworks insert the required information automatically. For example
注意 - 这是假设您正在制作 API。一些 API / 框架会自动插入所需的信息。例如
//the db.transaction method
function transaction(param, callback) {
//do code stuff
callback(someInternalId); //callback is the function you pass as the first parameter
}
So, if you want to pass your own data in the callback, wrap it in a function. Otherwise, the code you are using may be doing this for you automatically.
因此,如果您想在回调中传递自己的数据,请将其包装在一个函数中。否则,您使用的代码可能会自动为您执行此操作。
回答by TheTechy
I like to keep things very simple so I use a limited number of functions when handling storage on phonegap applications that can receive parameters. A lot of the examples I have seen have calls to many sub functions and for me, this is a nightmare when it comes to debugging.
我喜欢让事情变得非常简单,所以在处理可以接收参数的 phonegap 应用程序上的存储时,我使用了有限数量的函数。我见过的很多例子都调用了许多子函数,对我来说,这是调试时的噩梦。
I was caught out an a number of issues around Web SQL but reading the specs really, really helped clarify what I could and couldn't do. (http://www.w3.org/TR/webdatabase/)
我发现了许多有关 Web SQL 的问题,但阅读规范确实非常有助于阐明我能做什么和不能做什么。( http://www.w3.org/TR/webdatabase/)
Look at this simple code for an insert function:
看看这个插入函数的简单代码:
function dbInsert(param1, param2, dbObj) {
val1 = param1;
val2 = param2;
val3 = String(dbObj.item2);
var sqlTxt = "INSERT INTO demo (geo1, geo2, geo3) VALUES (?, ?, ?)";
db.transaction(function(tx) {tx.executeSql(sqlTxt,[val1,val2,val3])}, errorCB, successCB);
}
Lets just to walk through it. Obviously a standard function which receives parameters which can be anything, in this case an object as well a strings.
让我们来看看它。显然是一个标准函数,它接收可以是任何参数的参数,在这种情况下是一个对象和一个字符串。
sqlTxt is where the fun begins. Write this as you would normally write an insert statement, but where you would normally have the data to be inserted/selected etc in VALUESuse the ?placeholder for each field in the database tables you want to pass data into.
sqlTxt 是乐趣的开始。像通常编写插入语句一样编写它,但是通常在VALUES 中插入/选择数据的地方使用? 要将数据传递到的数据库表中每个字段的占位符。
Now lets break down the next line:
现在让我们分解下一行:
db.transaction(function(tx) {tx.executeSql(sqlTxt,[val1,val2,val3])}, errorCB, successCB);
When you create a new database, db is the handler to the database object so db.transactionasks to execute a transaction on the database db.
创建新数据库时,db 是数据库对象的处理程序,因此db.transaction要求在数据库 db 上执行事务。
If we write next next section like this you can see it's function that calls tx.executeSql and because it in execute inside the db.transactionmethod, it will be passed the db handle.
如果我们像这样编写下一节,您可以看到它调用 tx.executeSql 的函数,并且因为它在db.transaction方法中执行,它将传递 db 句柄。
function(tx) {
tx.executeSql(sqlTxt,[val1,val2,val3])
}
Now if we were to parse the sqlTxtit might look like this
现在,如果我们要解析sqlTxt,它可能看起来像这样
INSERT INTO demo (geo1, geo2, geo3) VALUES ('a', 'b', 'c');
and because we are passing the three variable in place of the ?holder, it looks like the line above. And finally you call error and success callback functions.
并且因为我们传递了三个变量来代替? 持有人,它看起来像上面的线。最后你调用错误和成功回调函数。
In your case I would create a queryDB function like this:
在你的情况下,我会创建一个这样的 queryDB 函数:
function queryDB(id) {
var sqlTxt = "SELECT * FROM DEMO WHERE id=?"
db.transaction(function(tx) {tx.executeSql(sqlTxt,[id])}, errorCB, successCB);
}
In essence, the function grabs the parameter id, passes it into the query in the [id] and executes and returns error or success. Obviously you can extend this to use multiple parameters or if you want to be really clever, you just create a single database transaction function and pass in the sql and the parameters to use as an object or array (Example will be on my blog this weekend)
本质上,该函数获取参数 id,将其传递到 [id] 中的查询中并执行并返回错误或成功。显然,您可以扩展它以使用多个参数,或者如果您想变得非常聪明,您只需创建一个数据库事务函数并传入 sql 和参数以用作对象或数组(示例将在本周末在我的博客上)
回答by Rene Weteling
Ok first of all create a class hat will handle you're db instances (db updates etc) this class will hold a function that you will use for all you're query's
好的,首先创建一个类 hat 将处理你的数据库实例(数据库更新等)这个类将保存一个函数,你将用于所有查询
self.db = window.openDatabase( // and so on
then the function:
那么函数:
// execute a query and fetches the data as an array of objects
self.executeQuery = function(string, args, callback, callbackparams) {
var self = this;
//console.log('db execute: '+string);
self.db.transaction(function(tx) {
tx.executeSql(string, args, function(tx, result) {
var retval = [];
for (var i = 0; i < result.rows.length; ++i) {
retval.push(result.rows.item(i));
}
if (callback) {
callback(retval, result, callbackparams);
}
}, self.error);
});
}
then when u have initiated you're class (i named it myDb) go apeshit!
然后当你发起你的班级(我将它命名为 myDb)时,去吧!
myDb.executeQuery('select l.* from location l inner join item_location il on (il.location_id = l.id and il.item_id = ?)', [item.id], function(locations, res, item){
item.locations = locations;
myDb.executeQuery('select * from media where item_id = ?', [item.id], function(media, res, item){
item.media = media;
// create item.
createItem(item);
}, item);
}, item);
as you can see the executeQuery has 4 params, query, params for query, callback (with 3 params, result, status and myparam) myparam (for callback)
如您所见,executeQuery 有 4 个参数,查询,查询参数,回调(有 3 个参数,结果,状态和 myparam) myparam(用于回调)
It took me some time to fix this, but when you've done this! no more annoying db horror!
我花了一些时间来解决这个问题,但是当您完成此操作后!不再烦人的db恐怖!
回答by Jon
We can't send any paramenter for queryDB function like "queryDB(id)"
我们无法为 queryDB 函数发送任何参数,例如“queryDB(id)”
I solved this issue by this way.
我通过这种方式解决了这个问题。
var contactId = 33
dbInst.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS CONTACT_REFERENCE (id unique)');
var sqlStr = 'INSERT INTO CONTACT_REFERENCE (id) VALUES (?)'
tx.executeSql(sqlStr, [contactId]);
}, errorCB, successCB);
回答by KickerKeeper
I think everyone comes close to answering your question. Really you need one slight modification to JohnP's answer. You should pass in the SQLTransaction Object that carries the executeSQL function. So to build on John's answer:
我想每个人都接近回答你的问题。确实,您需要对 JohnP 的答案稍作修改。你应该传入带有executeSQL函数的SQLTransaction Object。因此,以约翰的回答为基础:
var id = 'THEID';
db.transaction(function(tx){
queryDB(tx, id)
}, errorCB);
Then where you define the function you can grab your id param with an extra variable.
然后在你定义函数的地方你可以用一个额外的变量来获取你的 id 参数。
queryDB: function (tx, id) { ...your code... }
回答by Dina Salah
This is a worked solution:
这是一个有效的解决方案:
var sqltxt= 'INSERT INTO CONTACTS(id, data) VALUES (?, ?)';
var db = window.openDatabase("Database", "1.0", "Demo", 200000);
db.transaction(function(tx){tx.executeSql('DROP TABLE IF EXISTS CONTACTS');
tx.executeSql('CREATE TABLE IF NOT EXISTS CONTACTS(name unique, password)');
tx.executeSql(sqltxt,[name, pass]);
}, errorCB, successCB);