我正在使用 jquery 更改 main.php 文件中的 div 内容,而无需刷新页面, 但这里的问题是在加载的新 div 中包含一个表单,在表单操作中我希望将表单提交到同一页面(div),但被重定向到我不想要的 main.php 。我必须对操作进行哪些更改才能保持在具有相同 div 的同一页面上。
这是我用来动态更改 div 的代码。
main.php:
<li id="nav-home"><a class="button" href="main.php">Home</a></li>
<li id="nav-page1"><a class="button" href="page1.php">Page1</a></li>
<li id="nav-page2"><a class="button" href="page2.php">Page2</a></li>
<li id="nav-page3"><a class="button" href="page3.php">Page3</a></li>
<script>
$(function(){
$('.button').on('click', function(e){
e.preventDefault();
$('#content').load($(this).attr('href'));
});
})
</script>
示例:当我单击 main.php 中的 Page1 时,div 内容将被 page1 替换,其中 page1 中我有一个表单,当我提交表单时我想保留在同一页面中。
这是处理 page1 中表单的代码:
<form name="form" id="form" method="POST" action=""> //my form elements </form>
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
debug: false,
rules: {
//rules
},
messages: {
//messages
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('scripts/formhandler.php', $("#form").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
最佳答案
您可以使用 form.submit 函数,并使用 ajax 处理提交
$('#form_id').submit(function()
{
e.preventDefault(); // Prevent the default form action
/*now add ajax code here to do form submit*/
});
当然,如果您在页面加载后加载表单,则需要使用 jquery.live 或 jquery.on 函数来设置表单处理程序,而不是上面的代码。示例:
$('#form_id').on('submit', function()
{
// Code in here
});
您可以从 jquery 站点阅读有关 .live 和 .on 的更多信息
关于php - 当使用 jquery 更改 div 内容时,div 中的表单操作会带到主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12338011/