del*_*lmi 11 database jquery html5 web-sql
我有以下代码获取json记录集并在客户端Web Sql存储上的三个不同表中插入一些数据.
如何拦截databaseSync()函数的结束?我想要做的是显示一个警报或更好的ajax微调器gif,以便在同步完成时通知用户.
非常感谢你的帮助,ciao!
function databaseSync() {
// table one
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=one", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
// table two
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=two", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
// table three
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=three", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*ins 13
好的,这是我的第五次修订,但我喜欢这个问题而且我不断提出更好的想法.这个使用jquery延迟对象,我认为它最终涵盖了所有情况,并以它应该的方式工作.
function tableInsert(url) {
var dfd = $.Deferred();
var arr = [];
$.getJSON(url, function(json) {
$.each(json.results, function(i, res) {
var dfd = $.Deferred();
arr.push(dfd.promise());
db.transaction(function(tx) {
tx.executeSql(
"INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ",
[res.A, res.B, res.C, res.D],
function(){
onSuccess(dfd.resolve);
},
function(){
onError(dfd.resolve);
}
);
});
});
$.when.apply(this, arr).then(dfd.resolve);
});
return dfd.promise();
}
function databaseSync() {
$.when( tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=one"),
tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=two"),
tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=three"))
.then(function(){
console.log( 'All processing complete' );
});
}
Run Code Online (Sandbox Code Playgroud)
为了实现这一点,您需要更改onSuccess和onError,以便在执行其他任何操作之后执行resolve函数作为回调函数,然后这应该适合您.希望这个对你有帮助.