我在尝试在 Sqlite 中验证我的 Web 表单的某些部分时遇到了时间问题。
function submitForm()
{
var isValid = validateK2();
if(isValid)
submitK2();
}
function validateK2()
{
db.transaction(function(tx){
tx.executeSql("Select * From K2", [], function(tx, result){
if (results meet my criteria)
return true;
else
return false;
}, onSqlError);
});
}
但在 if (isValid...) 代码执行时,它返回 undefined,因为 validateK2 函数尚未完成执行,因此尚未返回 true 或 false。我在这里想念什么?
编辑:该网站是一个门户网站,允许员工从文件菜单中选择填写。提交后,他们可能会提交 1 个或 5 个表单。所以@CL 是正确的,我可以在 executeSql 回调中提交,而不是返回 true 然后提交。但是,根据所选文档,我可能需要运行更多验证,这意味着我需要一种动态方法来验证每个文档,并且在“提交”表单之前能够检查所有文档是否有效。所以这就是我所做的:
var submitFinalTimeout;
var doc1IsValid;
var doc2IsValid;
var selectedDocCount = selectedDocs.length \\selectedDocs is an array containing all the documents that have been selected and completed
function ValidateForm()
{
submitFinalTimeout = window.setTimout(submitFinal, 3000);
if(selectedDocs.indexOf("Doc1") != -1)
validateDoc1();
if(selectedDocs.indexOf("Doc2") != -1)
validateDoc2();
}
function validateDoc1()
{
db.transaction(function(tx){
tx.executeSql("Select * From Doc1Data", [], function(tx, result){
if (results meet my criteria)
doc1IsValid = true;
selectedDocCount--;
if(selectedDocCount != 0)
{
window.cancelTimeout(submitFinalTimeout);
submitFinalTimeout = window.setTimeout(submitFinal, 3000);
}
}, onError);
});
}
function validateDoc2()
{
db.transaction(function(tx){
tx.executeSql("Select * From Doc2Data", [], function(tx, result){
if (results meet my criteria)
doc2IsValid = true;
selectedDocCount--;
if(selectedDocCount != 0)
{
window.cancelTimeout(submitFinalTimeout);
submitFinalTimeout = window.setTimeout(submitFinal, 3000);
}
}, onError);
});
}
function submitFinal()
{
if (doc1IsValid && doc2IsValid)
submitForm();
}