大家好,我知道,如果页面上只有一个表单,很容易提交表单而无需刷新,但是如果页面上有多个表单怎么办。我使用以下代码提交表单,如果页面上只有一个表单,它可以正常工作。当页面上有多个表单时,如何更改它以使其正常工作。提前致谢。
function processForm() { $.ajax( { type: 'POST', url: form_process.php, data: 'user_name=' + encodeURIComponent(document.getElementById('user_name').value), success: function(data) { $('#message').html(data); } } ); } <form action="" method="post" onsubmit="processForm();return false;"> <input type='text' name='user_name' id='user_name' value='' /> <input type='submit' name='submit' value='submit'/> </form> <div id='message'></div>
只需自定义函数并添加参数formid即可在函数内获取表单数据以进行传递processForm("id of the form");
formid
processForm("id of the form");
function processForm(formId) { //your validation code $.ajax( { type: 'POST', url: form_process.php, data: $("#"+formId).serialize(), success: function(data) { $('#message').html(data); } } ); } <form action="" id="form1" method="post" onsubmit="processForm('form1');return false;"> <input type='text' name='user_name' id='user_name' value='' /> <input type='submit' name='submit' value='submit'/> </form> <form action="" id="form2" method="post" onsubmit="processForm('form2');return false;"> <input type='text' name='user_name' id='user_name' value='' /> <input type='submit' name='submit' value='submit'/> </form> <form action="" id="form3" method="post" onsubmit="processForm('form3');return false;"> <input type='text' name='user_name' id='user_name' value='' /> <input type='submit' name='submit' value='submit'/> </form> <div id='message'></div>