您的位置:首页 > 编程语言 > PHP开发

AJAX实现页面无刷新发表评论(post请求,服务器端使用php)

2014-12-20 14:53 751 查看
接受评价的表单所在的页面代码:

index.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>index</title>
<script type="text/javascript">
function postCCInsert()
{
// 创建XMLHttpRequest对象
var xmlhttp;
if (parent_word.length==0 || c_etymology.length == 0)
{
return;
}
if (window.XMLHttpRequest)
{// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// 创建url,因为这个处理评价内容的php文件和这个接受评价的文件处在同一个文件夹,所以直接用文件名就行
var url = "comment.php";
//打开连接
xmlhttp.open("POST", url, true);

var username = document.getElementById("userid").value;
var comment = document.getElementById("commentid").value;
// 不同参数之间用&连接,"username="里的username和"&comment="里的comment必须和表单里对应的输入框
// 名称必须一致
var postStr ="username=" + username + "&comment=" + comment;
// 这个添加头的语句对post方法传递参数来说是必须的,不然的话会出错
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 传递参数
xmlhttp.send(postStr);
// 验证请求是否成功
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// 把评价添加到网页所
document.getElementById("user_id").innerHTML=user_id;
document.getElementById("comment_id").innerHTML=comment_id;
}
}
}
</script>
</head>
<body>
 <p>网页文字</p>

<!-- 用于显示评价的标签 -->
<p id = "user_id"></p>
<p id = "comment_id"></p>

<form>
用户名:
<input type='text' id = 'userid' name='username' />
<br/>
评论:
<textarea id = "commentid"  name = "comment" rows='5' cols='81'></textarea>
<input type="button" onclick="postCCInsert()" value='提交'>
</form>

</body>
</html>


运行这个文件的代码后出现下面图片中样子:



点击“提交”之后,就把评价的内容交给comment.php处理。comment.php仅仅把评价保存到数据库中,而且comment.php这个页面并不会弹出,只是在后台处理,依旧停留在index.php页面上。下面是comment.php的代码:

<?php
// 把数据存入数据库表中
$conn = mysql_connect ( "localhost:3306", "数据库用户名", "数据库密码" );
if (! $conn) {
echo "failed to connect";
}
mysql_select_db ( "dictionary", $conn );
$username = $_POST["username"];
$comment = $_POST['comment'];
// 表就两列,一列保存的是用户名,另一列保存评价
$sql = "INSERT INTO tablename VALUES (\"$username\", \"$comment\")";
mysql_query ( $sql );
mysql_close ( $conn );
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  服务器 php ajax 数据库