1

我有 2 个输入字段“用户”和“评论”,我希望使用 AJAX 异步保存用户输入,因此无需刷新。到目前为止,我已经将它添加到数据库中,但由于某种原因它是空的。我相信原因是我没有正确附加值。

HTML(JS在head标签之间):

<p>User: <input type="text" id="userName" /></p>
<p>Comment : <input type="text" id="comment" /></p>
<input type="button" value="Submit" onclick="callServer();" />

JS:

function callServer(){
  var usr = document.getElementById("user").value;
  var cmnt = document.getElementById("comment").value;
  var ajaxRequest = XMLHttpRequest();

  ajaxRequest.open("POST", "insert.php", true);
  ajaxRequest.send(null);
}

PHP:

<?php
// Setting variables for the elements
$user = $_POST['user'];
$comment = $_POST['comment'];

// Establishing connection and selecting db    
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db('local',$con);

// Doing the query for the insert
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comment')");

mysql_query($query, $con);
mysql_close($con);
?>
4

2 回答 2

1

您的输入 ID 是userName,但您的目标是user

改成:

var usr = document.getElementById("userName").value;

您还null使用 ajax 请求发送,您应该发送数据:

var params = "user=" + encodeURIComponent(usr) + "&comments=" + encodeURIComponent(cmnt);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajaxRequest.send(params);

此外,您应该包括内容类型标头 - 如上所述。

最后,不推荐使用 mysql_* 库,您应该使用现代 API,例如 PDO 或 MySQLi 进行任何新的开发。因为您使用的是这个库,所以您需要为 SQL 注入转义发布数据:

$user = mysql_real_escape_string($_POST['user']);
$comment = mysql_real_escape_string($_POST['comment']);

如果您使用现代 API,则可以执行参数化查询,而无需您手动转义任何内容。

也刚刚注意到,删除这一行:

mysql_query($query, $con);

在此之前,您已经在该行上执行了查询。此行无用并且会失败,它正在尝试使用第一个查询的结果资源执行另一个查询。

于 2012-11-19T14:53:59.037 回答
0

我会开始研究 Jquery,它对 javascript/Ajax 部分有很大帮助。

这里的问题是你永远不会在 AJAX 调用中发送变量,你需要这样的东西:

ajaxRequest.send(postvariables);
于 2012-11-19T14:54:45.760 回答