gpt4 book ai didi

javascript - AJAX HTTP GET 请求必须触发两次才能工作

转载 作者:可可西里 更新时间:2023-11-01 17:27:25 30 4
gpt4 key购买 nike

我正在编写一个 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();
}
?>

附言:请不要费心指出 sql 输入卫生或其他我还没有做到的事情。请仅回答此 http 请求处理错误。谢谢。

最佳答案

onreadystatechange 是一个事件处理程序,因此应该引用一个函数。在您的代码中,您引用了 handleReceiveChathandleSendChat 的结果,它们都没有返回任何内容,因此 undefined。尝试更改为以下内容:

receiveReq.onreadystatechange = handleReceiveChat

sendReq.​​onreadystatechange = handleSendChat;

第二次调用似乎正常,但是,代码将使用第一次调用的响应(因为第二次响应尚未完成)。

关于javascript - AJAX HTTP GET 请求必须触发两次才能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423879/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com