onsubmit返回false不起作用

以下脚本正确显示错误消息,但表单始终提交confirm_shop_code()返回true还是false 。 我试过很多方法来解决这个问题,但它仍然存在。 我必须在表单返回false时停止提交,但允许它在返回true时提交。 请任何人帮我解决这个问题?

 

<input type="text" class="form-control" id="shop" name="code" value="code; ?>" placeholder="Enter Shop Code">
function confirm_shop_code(){ var code=document.getElementById( "shop" ).value; if(code) { $.ajax({ type: 'post', url: 'validations.php', data: { shop_code:code, }, success: function (response) { $( '#shop_data' ).html(response); if(response=="OK") { return true; } else { return false; } } }); } else { $( '#shop_data' ).html(""); return false; } } query($query) or die($db->error); $count = $result->num_rows; if($count > 0) { echo "SHOP CODE already Exists"; } else { echo "OK"; } exit; ?>

它提交的原因是因为AJAX调用默认是异步的。 我不建议将它同步,因为这将阻止javascript执行的其余部分。 此外,您从$.ajaxsuccess方法返回false 。 这与父函数的范围不同,因此也不会导致父函数返回false 。 所以事实上,你的confirm_shop_code()函数没有返回任何东西,除非code是假的,这就是为什么你的表单总是被提交,无论AJAX调用发生了什么。

我建议使用jQuery绑定到表单的提交事件,并使用preventDefault()禁用表单提交。 首先,只需在表单中添加一个id属性(例如"yourform" ),然后执行以下操作:

 $("form#yourform").submit(function(e) { e.preventDefault(); var form = $(this); var code=document.getElementById( "shop" ).value; if(code) { $.ajax({ type: 'post', url: 'validations.php', data: { shop_code:code, }, success: function (response) { $( '#shop_data' ).html(response); if(response=="OK") { form.unbind('submit').submit() } } }); } else { $( '#shop_data' ).html(""); } }); 

您需要在ajax代码中添加async:false

 function confirm_shop_code(){ var code=document.getElementById( "shop" ).value; var stopSubmit = false; if(code) { $.ajax({ type: 'post', url: 'validations.php', async:false, data: { shop_code:code, }, success: function (response) { $( '#shop_data' ).html(response); if(response=="OK") { stopSubmit = false; } else { stopSubmit = true; } } }); } else { $( '#shop_data' ).html(""); stopSubmit = true; } if(stopSubmit){ return; } }