这是我的 jquery 代码片段。实际上,我会检查提交表单上的字段是否为空,然后如果用户名存在则显示确认对话框。
<script type="text/javascript">
jQuery(function(){
$("#form").submit(function(){
var isFormValid = true;
if ($.trim($("#telephone").val()).length == 0){
isFormValid = false;
alert("Empty telephone!");
}
elseif(check_field() == 1){
if(confirm('Delete?')){
isFormValid = true;
}else{
isFormValid = false;
}
return isFormValid;
});
function check_field(){
var field = $('#field').val();
$.post("check_field.php", { field: field }, function(result){
//if the result is 1
if(result == 1){
return 1;
}else{
return 0;
}
});
}
});
</script>
最佳答案
一个典型的错误,你需要在ajax函数中进行回调,因为当函数执行完毕后,ajax post还没有进行:
function check_field(callback){
var field = $('#field').val();
$.post("check_field.php", { field: field }, function(result){
//if the result is true
callback(result == 1);
});
}
然后是这样的:
$("#form").submit(function(e){
e.preventDefault() // prevent the form from submitting... yet
var $form = $(this);
check_field(function(result) {
if(result && confirm('Delete?')) {
$form.submit(); // now submit it
}
});
});
欢迎来到异步编程的世界!
关于javascript - jquery 检查字段并确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277923/