php提交表单无刷新显示提交的数据
在提交表单时,我们不希望页面跳转或是刷新就能看到已已经提交成功的数据,这个功能实现起来其实很简单,一个静态页面提交表单,一个php动态页面接收处理数据,再加上一段js代码就可以了。具体如下:
1、先新建一个静态表单页面:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>php提交表单无刷新显示提交的数据</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="myForm" method="post">
Name: <input name="name" id="name" type="text" /><br />
Phone:<input name="phone" id="phone" type="text" /><br />
Address: <input name="address" id="address" type="text" /><br />
Delivery Time: <input name="dely_time" type="radio" value="morning">Morning(9-12)
<input name="dely_time" type="radio" value="afternoon">Afternoon(12-18)
<input name="dely_time" type="radio" value="night">Night(18-20)<br />
<input type="button" id="submitData" onclick="SubmitFormData();" value="Submit" />
</form>
<br/>
<div id="results">
<!-- 提交成功后的数据在这里显示 -->
</div>
</body>
</html>
2、静态表单页面中还需要一段js代码:
<script src="//code.jquery.com/jquery-latest.js"></script>
<script>
function SubmitFormData() {
var name = $("#name").val(); //表单元素id name
var phone = $("#phone").val(); //表单元素id phone
var address = $("#address").val();//表单元素id address
var dely_time = $("input[type=radio]:checked").val(); //表单选项元素radio
$.post("submit.php", { name: name, phone: phone, address: address, dely_time: dely_time },//提交到submit.php
function(data) {
$('#results').html(data); //数据返回显示元素id
$('#myForm')[0].reset(); //form表单id
});
}
</script>
3、php处理页面submit.php,处理成功返回数据,不成功进行提示:
<?php
/* php进行数据操作处理,如插入数据库*/
/* 假设数据库操作结果为$res */
if( $res ){
echo "已成功將数据写入数据库!写入的数据是:<br />";
echo $_POST['name'] ."<br />";
echo $_POST['phone'] ."<br />";
echo $_POST['address'] ."<br />";
echo $_POST['dely_time'] ."<br />";
}else{
echo "提交处理失败";
}
?>
上面的静态页面和js合在一起就是:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>php提交表单无刷新显示提交的数据</title>
<meta charset="UTF-8" />
<script src="//code.jquery.com/jquery-latest.js"></script>
<script>
function SubmitFormData() {
var name = $("#name").val(); //表单元素id name
var phone = $("#phone").val(); //表单元素id phone
var address = $("#address").val();//表单元素id address
var dely_time = $("input[type=radio]:checked").val(); //表单选项元素radio
$.post("submit.php", { name: name, phone: phone, address: address, dely_time: dely_time },//提交到submit.php
function(data) {
$('#results').html(data); //数据返回显示元素id
$('#myForm')[0].reset(); //form表单id
});
}
</script>
</head>
<body>
<form id="myForm" method="post">
Name: <input name="name" id="name" type="text" /><br />
Phone:<input name="phone" id="phone" type="text" /><br />
Address: <input name="address" id="address" type="text" /><br />
Delivery Time: <input name="dely_time" type="radio" value="morning">Morning(9-12)
<input name="dely_time" type="radio" value="afternoon">Afternoon(12-18)
<input name="dely_time" type="radio" value="night">Night(18-20)<br />
<input type="button" id="submitData" onclick="SubmitFormData();" value="Submit" />
</form>
<br/>
<div id="results">
<!-- 填入表單內容會秀在這 -->
</div>
</body>
</html>
这样配合submit.php这个动态页面就可是无刷新提交数据并显示数据了!