鉴于您没有提供表格,只能做出假设。
<form id="some_form" action="page2.php" method="post">
<input type="text" name="user_name"/>
//a collection of form elements
<form>
然后使用 ajax,并捕获表单提交事件,同时阻止它的默认操作
$(document).on('submit', '#some_form', function(e){
e.preventDefault(); //stop form from redirecting, also stops sending of data
var $this = $(this); // cache form object for performance
$.ajax({
url: $this.prop('action'),
type: $this.prop('method'),
data: {
handle_form: 'ajax',
form_data : $this.serializeArray()//array of objects
},
success:function(data){
//data is what is returned from the server if successful
}
});
return false; //just another example of stopping form submit, don't need both
});
然后在您的 page2.php 文件中,检查是否存在一个字段。
if(isset($_POST['user_name']) && $_POST['handle_form'] == 'ajax'):
//your form is trying to be submit
//handle the submission
echo 'We submit the form!'; //is the 'data' in our success function
elseif(isset($_POST['user_name']) && !isset($_POST['handle_form'])):
//regular form submission, no ajax, no javascript.
endif;