【发布时间】:2009-11-18 22:22:36
【问题描述】:
我正在尝试让它工作,但我遇到了问题。我在这里错过了什么?
我正在尝试通过 jQuery 将一些数据插入到本地 MySQL 表中。如果我自己运行 save.php,它会在数据库中插入一个空白行,这样就可以了。有什么想法吗?
**index.php**
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form#submit').submit(function () {
var nume = $('#nume').val();
$.ajax({
type: "POST",
url: "save.php",
data: "nume="+ nume,
success: function() {
$('#nume').val('');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="submit" method="post">
<p>Nume: <input id="nume" name="nume" type="text"></p>
<p><input id="submitButton" type="button" value="Submit"></p>
</form>
</body>
</html>
**save.php**
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$nume = htmlspecialchars(trim($_POST['nume']));
$add = "INSERT INTO ajax_test (nume) VALUES ('$nume')";
mysql_query($add) or die(mysql_error());
?>
【问题讨论】:
-
我建议您更改编辑器的首选项以使用 4 空格缩进。
-
我知道这只是测试代码,但请确保在您完成的代码中使用
mysql_real_escape_string()转义$nume,否则您将遇到SQL 注入漏洞。