我正在写一个ajax聊天程序,我有一个奇怪的错误。我必须两次调用GET请求才能正确处理它。它第一次被触发时似乎对服务器做出了很好的响应,但它不会激活分配给onreadystatechange [getChatText()]的函数,直到它第二次被调用。不确定是什么导致它,我想你们可以帮忙。
下面的代码。
使用Javascript:
var recieveReq = getXmlHttpRequestObject();
var sendReq = getXmlHttpRequestObject();
var lastMessage = "NULL";
var mTimer;
//Create XMLHTTP Object
function getXmlHttpRequestObject() {
return new XMLHttpRequest();
};
//GET & POST creation
function getChatText() {
if (recieveReq.readyState == 4 || recieveReq.readyState == 0) {
recieveReq.onreadystatechange = handleRecieveChat();
recieveReq.open("GET", 'chat.php?chat=1', true);
recieveReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
recieveReq.send(null);
};
};
function sendChatText() {
if(document.getElementById('text_message').value == '') {
alert("You have not entered a message");
return;
};
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.onreadystatechange = handleSendChat();
sendReq.open("POST", 'chat.php?send=1', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var param = '&message=' + document.getElementById('text_message').value;
sendReq.send(param);
document.getElementById('text_message').value = '';
};
};
//Handle Send & Receive
function handleRecieveChat() {
if (recieveReq.readyState == 4 && recieveReq.status == 200) {
var chatDiv = document.getElementById('div_chat');
var tempResponse = recieveReq.responseText;
var response = tempResponse.replace(/\\\//g,"/");
if (response != lastMessage) {
chatDiv.innerHTML = response;
};
chatDiv.scrollTop = chatDiv.scrollHeight;
lastMessage = response;
mTimer = setTimeout('getChatText();', 5000);
};
};
function handleSendChat() {
clearInterval(mTimer);
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
getChatText();
}
};
function resetChat() {}; //Empty for now
document.onload = getChatText();
PHP:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/plain; charset=utf-8");
$connect = mysqli_connect("localhost", "user", "password", "database");
if (!$connect) {
die('Could not connect: ' . mysqli_connect_errno($connect));
}
if(isset($_GET["chat"])) {
$sql = "SELECT * FROM message ORDER BY message_id;";
$result = mysqli_query($connect, $sql);
$row = mysqli_fetch_array($result);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$time = substr($row['post_time'], 0, 5);
echo "<span style=color:".$row['user_color'].">".$row['user_name']."</span> (".$time."): ".$row['message']."<br>";
}
}
$connect->close();
}
if(isset($_POST['message']) && $_POST['message'] != '') {
$sql = "INSERT INTO message (chat_id, user_id, user_name, message, post_time, user_color) VALUES (1, 3, 'Riley', '".$_POST['message']."', NOW(), '#29D410');"; //Couple are default for testing purposes
$result = mysqli_query($connect, $sql);
echo $sql;
$connect->close();
}
?>
PS: 请不要理会指出sql输入卫生或其他我尚未得到的东西。请回答这个http请求处理错误。感谢。
答案 0 :(得分:1)
onreadystatechange
是一个事件处理程序,因此应该引用一个函数。在您的代码中,您引用了handleReceiveChat
和handleSendChat
的结果,它们都没有返回任何内容,因此undefined
。请尝试更改为以下内容:
receiveReq.onreadystatechange = handleReceiveChat
sendReq.onreadystatechange = handleSendChat;
看起来似乎第二次调用正在运行,但是,代码将使用第一次调用的响应(因为第二个响应尚未完成)。