我已经看到了关于这个主题的几个问题和答案。但经过几个小时的测试..。没有人为我工作过..谁能帮助我解决我的问题!??
$(document).ready(function() {
$( "#search_form" ).on('submit',function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: "ajax_validate.php",
type: 'POST',
data: {host:host},
dataType: 'json',
success: function (data) {
if (data.status == 'ok'){
form.submit();
}
});
});
这给了我一个无限的循环。我的任务是:-阻止表单提交的默认操作。-如果data.status == ok,则提交表单。
发布于 2018-06-01 04:22:25
$('form').on('submit', function(e){
e.preventDefault();
console.log('submit prevented');
setTimeout(function(){
//submit the underlying form element to bypass the jquery handler
e.target.submit();
}, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://stackoverflow.com/questions/50632085/jquery-ajax-form-not-submitting-after-using-preventdefault">
<button>Submit me</button>
</form>
因此,利用这个概念,您应该能够将您的代码更改为以下代码。
$(document).ready(function() {
$( "#search_form" ).on('submit',function(event) {
event.preventDefault();
var form = this; //This line changed from "$(this)" to just "this"
$.ajax({
url: "ajax_validate.php",
type: 'POST',
data: {host:host},
dataType: 'json',
success: function (data) {
if (data.status === 'ok'){
form.submit();
//or optionally you could do
//event.target.submit();
//both "this" and "event.target" should point to the form submitted
}
}
});
});
});
顺便说一句,当我复制您的逻辑以显示更改时,有一个语法错误,您的成功参数没有正确关闭。请确保您正确地关闭了所有内容,并且您的控制台不会告诉您任何错误。
发布于 2018-06-01 06:28:31
我尝试了Toplars的答案,但仍然得到错误:
Uncaught TypeError: event.target.submit is not a function
Uncaught TypeError: form.submit is not a function
我让它工作的唯一方法是在函数中抛出ajax查询,然后根据函数的结果来允许或拒绝POST。我还必须添加'async:false‘来强制ajax等待查询的响应,以允许code = variable实现。代码见下文:
var x = ajax();
if(x == 0){
event.preventDefault();
}
function ajax(){
code = null;
$.ajax({
url: "ajax_validate.php",
type: 'POST',
async:false,
data: {host:host},
dataType: 'json',
success: function (data) {
if (data.status == 'ok'){
code = 1;
}else if(data.status == 'error'){
code = 0;
}
});
return code;
}
https://stackoverflow.com/questions/50632085
复制相似问题