我一直在寻找一段时间让它发挥作用。 (5天)所以我通过带有下一个和后退按钮的ajax在同一个div中加载我的网站页面。所有div信息都是表单数据。我需要添加一个jquery ajax函数来获取表单数据并提交到我的php文件进行处理。请记住,每次单击按钮时,表单数据都是新的。问题是如何在适当的事件处理程序中放置ajax函数,并在其他ajax调用重新加载不同的表单之前将其发送到php。
已加载表单(表格多种多样)
<form id="myForm" method="post" action="pages/student_info/ps1.php">
<fieldset>
<legend>Legal Name</legend>
<label for='firstname'>First Name: </label>
<input type='text' name='firstname'
id='firstname'minlength="2"required/>
<br>
<label for='lastname'>Last Name: </label>
<input type='text' name='last-name' id='last-name' required/>
<br>
<label for='mi'>Middle Initial: </label>
<input type='text' name='mi' id='mi' />
<br>
<br>
<legend>Gender</legend>
<label for="studentmale">Male</label>
<input type="radio" name="studentgender" id="male" value="M" required/>
<br>
<label for="studentfemale">Female</label>
<input type="radio" name="studentgender" id="female" value="F">
<br>
</fieldset>
</form>
Jquery的
$(document).ready(function()
{
//submit form with button click
$("#next").click(function(){
$("#myForm").submit();
});
$("#myForm").on( "submit", "form", function(e) {
e.preventDefault();
$.ajax({
dataType: "json",
type: 'POST',
url: $('#myForm').attr("action"),
data: $('#myForm').serializeArray(), // getting filed value in
serialize form
})
.done(function(data){ // if getting done then call.
// show the response
alert(data);
})
.fail(function() { // if fail then getting message
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
页面导航功能在我可以停止表单注入之前运行
//This code runs when a back or next button has been pressed
$("#next, #prev").click(function(){
var max =$('#next').data("max");
max = parseInt(max);
currentPage = ($(this).attr('id')=='next') ? currentPage + 1 :
currentPage - 1;
// ALL DATA VALIDATION DONE ON THIS ONE LINE
var formStatus = $('#myForm').validate().form();
...much more code here but it all runs navigation just fine
答案 0 :(得分:0)
你的代表团在这一行上是不正确的:
$("#myForm").on( "submit", "form", function(e) {
正在寻找 #myForm
内的表单,但myForm
是表单。另外,因为你说你替换了整个表格,听众将在替换时丢失
委托一个始终存在的更高级别的祖先并定位#myForm
$(document).on( "submit", "#myForm", function(e) {