我像这样制作index.php:
<script src="js/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#sload").load('save1.php',function(forma){
$(".csave").click(function(){
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
})
return false;
});
});
});
</script>
<a href="#" class="csave">SAVE</a>
<div id="sload"></div>
save1.php是这样的:
<table>
<form method="post" name="form1" id="form1" action="input1.php">
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</form>
和input1.php
<? session_start();
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>
单击SAVE后不是错误,但数据库存储在空字段中。表单加载后为空白提交表单
感谢。
答案 0 :(得分:0)
您需要将加载和保存的逻辑分开,如下所示:
以下是一个示例(基于您的代码)作为单页脚本 test.php :
<?php
// Load Form
if (isset($_GET['loadForm']))
{
exit('<form method="post" name="form1" id="form1" action="test.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>');
}
// Handle Form Save
if (count($_POST) > 0)
{
// TODO
exit('got form data: '. print_r($_POST, true));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('test.php?loadForm');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
<a href="#" class="csave">SAVE</a>
<div id="sload"></div>
单击“保存”时,输出结果如下:
要完成此代码,请将db行插入代码添加到TODO
。希望这会有所帮助。
<强>更新强>
这是拆分版本:
<强>的index.php 强>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('save1.php');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
<a href="#" class="csave">SAVE</a>
<div id="sload"></div>
<强> save1.php 强>
<form method="post" name="form1" id="form1" action="input1.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>
<强> input1.php 强>
<?php
session_start(); // what's this for? you aren't using session on this file
// this is not safe! use mysqli or pdo and escape post values!!!
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>