从 jquery ajax 响应中获取值而不设置 async false
我正在使用 jquery 表单插件将数据提交到服务器。在提交之前,我通过 ajax 运行服务器端验证。所以结构是
function validateForm(formData, jqForm, options){
var check = true; //have to set check to false to avoid form submit
....
looping through form elements and putting values in to data array here
....
function sendData(callback){
$.ajax({
url:'validate.php',
data:data,
dataType:'json',
//async:false, if I uncomment this, code works as I want
success:callback
});
}
function processForm(response){
$.each(response,function(i,res){
//if validation is fail I'm setting check = false here
});
}
sendData(processForm);
return check;
})
因为我看到将 async 设置为 false 不是一个好的做法,所以如何使用回调将检查值设置为 false?
I'm using jquery form plugin to submit data to server. Before submitting I'm running server side validation via ajax. so the structure is
function validateForm(formData, jqForm, options){
var check = true; //have to set check to false to avoid form submit
....
looping through form elements and putting values in to data array here
....
function sendData(callback){
$.ajax({
url:'validate.php',
data:data,
dataType:'json',
//async:false, if I uncomment this, code works as I want
success:callback
});
}
function processForm(response){
$.each(response,function(i,res){
//if validation is fail I'm setting check = false here
});
}
sendData(processForm);
return check;
})
Since I saw setting async to false is not good practice, how can I set the check value to false using callbacks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要尝试返回数据。在回调内(或在您从中调用的函数中)执行需要执行的任何工作。
Don't try to return the data. Do whatever work needs doing inside the callback (or in functions you call from it).
你见过 jQuery
.submit()
函数吗?您可以通过调用.preventDefault()
取消验证失败的提交。示例 jQuery:
您可以分两个阶段进行验证和提交 - 首先验证,然后在
OnAJAXSuccess
处理程序中使用提交。Have you seen the jQuery
.submit()
function? You can cancel submission where validation fails by calling.preventDefault()
.Example jQuery:
You could do your validation and submission in two phases - validate first, then use submit in an
OnAJAXSuccess
handler.