jQuery AJAX自动提交表单 [英] JQuery AJAX auto submit form
问题描述
我正在尝试使用ajax发布表单,并且可以正常工作...但是当我尝试自动提交表单时,它不起作用... 如果我按下提交按钮..它很好..但是如果我setInterval("submitform();",5000); ajax不起作用(我是说它重新加载了页面).
Im trying to post a form with ajax and its working fine... but when i try to put to auto submit the form its not workin... If i press the submit button.. its fine.. but if i setInterval("submitform();", 5000); ajax doesnt work (i mean it reloads the page).
ajax.js
$(document).ready(function(){
$('#form1').submit(function(){
$.ajax({
url : 'inserir.php',
type : 'POST',
data : $('form').serialize(),
success: function(data){
$('#resultado').html(data);
}
});
return false;
});
})
form.html
form.html
<html>
<head>
<script type="text/javascript" src="ajax.js" ></script>
</head>
<body>
<form id="form1" method="POST">
Código: <br />
<input type="text" name="idVeiculo" id="idVeiculo" value="1"/>
<br /><br />
Nome: <br />
<input type="text" name="nome" id="nome" /><input type="submit">
</form>
<div id="resultado"></div>
<script type="text/javascript">
window.onload=function(){
setInterval("submitform();", 5000);
}
function submitform(){ document.getElementById('form1').submit(); }
</script>
</body>
</html>
所以,如果我按下按钮,它就可以正常工作... 如果我使用该自动提交功能,请重新加载页面,而不仅仅是将数据发布到php文件中.
So if i press the button, it works fine... If i use that auto submit function, reloads the page rather than just post the data to the php file.
感谢您的帮助!
推荐答案
来自MDN
https://developer.mozilla.org/zh- US/docs/Web/API/HTMLFormElement.submit
从基于Gecko的应用程序中调用此方法时,将不会触发表单的onsubmit事件处理程序(例如,onsubmit ="return false;").通常,不能保证HTML用户代理会调用它.
The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.
您应该将ajax调用分为一个函数,然后在超时函数中调用它
You should separate the ajax call into a function and just call it in the timeout function
$(document).ready(function(){
$('#form1').submit(ajax);
})
function ajax(){
$.ajax({
url : 'inserir.php',
type : 'POST',
data : $('form').serialize(),
success: function(data){
$('#resultado').html(data);
}
});
return false;
}
...
window.onload=function(){
setInterval(ajax, 5000);
}
这篇关于jQuery AJAX自动提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!