我正在尝试使用PHP,AJAX和JS创建一个聊天框。此处没有语法错误,但浏览器未显示所需的输出。在“消息加载中请等待”,没有发生替换。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>chat box</title>
</head>
<script>
function submitchat(){
if(form1.uname.value == "" || form1.msg.value ==""){
alert("All fields are mandatory!!!");
return;
}
var uname=form1.uname.value;
var msg=form1.msg.value;
var xmlHttp =new XMLHttpRequest();
XMLHttp.onreadystatechange = function(){
if(XMLHttp.readystate==1 && XMLHttp.status==200) {
document.getElementById('chatlog').innerHTML=XMLHttp.responseText;
}
}
XMLHttp.open('GET','insert.php?uname='+uname+'msg='+msg,true);
XMLHttp.Send();
}
</script>
<body>
<form name="form1">
Enter your chat name:<input type="text" name="uname" /><br /><br />
Your Message:<textarea name="msg" ></textarea>
<a href="#" onclick="submitchat()">send</a>
<div id="chatlog">
Loading chatlog please wait...
</div>
</body>
</html>
Insert .php code is
<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];
$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
mysql_query("INSERT INTO msg ('usernmae',msg') Values ('$uname','$msg')");
$result1=mysql_query("SELECT * FROM msg ORDER by id desc");
while($extract= mysql_fetch_array($result1)){
echo $extract['username'].":".$extract['msg']."<br>";
}
?>
答案 0 :(得分:0)
在这一行:
if(XMLHttp.readystate==1 && XMLHttp.status==200) {
尝试将readystate更改为4.根据文档:
0:请求未初始化
1:建立服务器连接
2:收到请求
3:处理请求
4:请求已完成且响应已准备好