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

来源:互联网 发布:彻底删除硬盘数据软件 编辑:程序博客网 时间:2024/04/26 08:29

接受评价的表单所在的页面代码:

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 );?>


0 2
原创粉丝点击