【发布时间】:2014-04-25 13:42:39
【问题描述】:
我想使用 ajax 将数据插入到表中,这样数据将在不重新加载页面的情况下插入。
这段代码很好地将数据插入到表中,但代码也会重新加载页面。
但我想插入而不重新加载页面。
我该怎么做?
<?php
include('connection.php');
if(isset($_POST['cmt'])){
$comment = addslashes($_POST['cmt']);
$alertid = $_POST['alert_id'];
mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
}
</script>
<form method = "POST" onsubmit = "submitform()">
<textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
<input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
<input type = "submit" name = "submit" value = "Comment">
</form>
【问题讨论】:
-
危险:您使用的是an obsolete database API,应该使用modern replacement。你也容易受到SQL injection attacks(
addslashes不够),现代 API 可以让你更容易地defend。 -
@AbhikChakraborty — 不会有任何好处,因为它不是 jQuery 事件处理程序。
-
@Quentin 是的,他正在使用 onsubmit 所以是的 return false 应该可以解决问题。
标签: javascript php jquery mysql ajax