我已经阅读了有关jQuery.ajax方法的信息,并相信这应该是我所需要的-但到目前为止,它尚无法正常工作.
我用表“ users”创建了一个测试mysql数据库,在该表中添加了“ name”和“ location”行,然后确保可以使用命令行将数据保存到该数据库.然后,我制作了一个带有按钮的测试页,并将此副本添加到我的脚本文件中($.ajax部分直接来自jQuery api示例):
$('#button').click(function(){
saveData();
});
function saveData(){
$.ajax({
type: "POST",
url: "process.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data was saved: " + msg );
});
}
我确实收到了一条警告消息,“数据已保存”,但实际上没有任何内容保存到我的数据库中.我一定对process.php做错了,但不确定是什么.这是process.php中的代码(我为数据库,db_host,用户等设置了变量,这些未在此处显示):
// 1. Create a connection to the server.
$connection = mysql_connect($db_host, $db_user,$db_pwd);
// make sure a connection has been made
if (!$connection){
die("Database connection failed: " . mysql.error());
}
// 2. Select the database on the server
$db_select = mysql_select_db($database, $connection);
if (!$db_select){
die("Database selection failed: " . mysql.error());
}
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}