Home > Article > Backend Development > PHP Ajax留言板
本案例代码已经提供下载,点击这里!
create table t_message(id int auto_increment primary key,email varchar(100),content text);
<div style="width:800px;margin:0 auto;"> <form action="#" > <fieldset> <legend>Leave Message Here</legend> <table> <tr> <td>Email:</td> <td><input name="email" id="email" type="email" /></td> </tr> <tr> <td>Content:</td> <td><textarea name="content" id="content" cols="80" rows="6" ></textarea></td> </tr> <tr> <td></td> <td><input name="button1" type="button" value="Post" onclick="doRequestUsingPOST()" /></td> </tr> </table> </fieldset> </form></div>
var xmlHttp; function createXMLHttpRequest(){ if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }else{ alert("浏览器不支持XMLHttpRequest对象"); } }
function createQueryString(){ var email = document.getElementById("email").value; var content = document.getElementById("content").value; var queryString = "email="+ email + "&content="+ content ; //alert(queryString); return queryString; }
function doRequestUsingPOST(){ createXMLHttpRequest(); var url = "message_ajax.php?timeStamp=" + new Date().getTime(); var queryString = createQueryString(); xmlHttp.open("POST",url,true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); xmlHttp.send(queryString); }
function handleStateChange(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ parseResult(); //alert("OK"); } } } function parseResult(){ var responseDiv = document.getElementById("newmessage"); if(responseDiv.hasChildNodes()){ responseDiv.removeChild(responseDiv.childNodes[0]); } var responseText = xmlHttp.responseText;//document.createTextNode(xmlHttp.responseText); responseDiv.innerHTML = responseText; //responseDiv.appendChild(responseText); }
<?php include_once("config.php"); $email = strip_tags($_POST['email']); $content = strip_tags($_POST['content']); $sql1 = "insert into t_message values(NULL, '" . $email . "' ,'".$content."')"; mysql_query($sql1); $sql = "SELECT * FROM `t_message` order by id desc LIMIT 10"; $result = mysql_query($sql); $responseText = "<table>"; while($message = mysql_fetch_array($result)){ $onemessage = " <tr> <th style='background-color:gray;'>Email:</th> <td>".$message['email']."</td> </tr> <tr style='border-bottom:1px gray dashed;'> <th style='background-color:gray;'>Content:</th> <td>".$message['content']."</td> </tr>"; $responseText = $responseText.$onemessage; } $responseText = $responseText."</table>"; echo $responseText;?>