我正在尝试为我的网站制作一个聊天框。基本上,用户将他们的聊天输入到带有 id chat-input 的文本区域。当用户单击 Enter 按钮时,它会调用 sendChat()
函数。此函数将请求发送到服务器上的一个 php 文件,该文件将用户的聊天记录添加到聊天记录(服务器上的一个文本文件)。成功后,javascript 应该调用 update() 函数,该函数对服务器上的 chatlog.txt 文件执行获取请求,并将其加载到 ID 为 prev-chats 的 div 中。问题是 javascript 在服务器响应之前调用了 update(),因此在页面刷新之前不会更新 prev-chats。我可以这么说是因为
a) 在我刷新页面之前,聊天不会更新,并且
b) 在 Google Chrome 中,按 F12 后,网络选项卡会在提交聊天的 POST 请求之前显示对 chatLog.txt 的 GET 请求。
这是我的 HTML 代码
<div id="prev-chats" class="well"></div>
<textarea id="chat-input"></textarea>
<button class="btn btn-default" onclick="sendChat()">Enter</button>
<button class="btn btn-default" onclick="update()">Update</button>
<script type="text/javascript">
function sendChat(){
var message = $("#chat-input").val();
var datavar = {"message": message};
console.log("Sending message to server");
$.ajax({
type: "POST",
async: "false",
url: "chatResponse.php",
data: datavar,
success: update()
});
console.log("Message sent to server");
};
function update(){
$("#prev-chats").load("chatLog.txt");
console.log("chat updated");
}
update();
</script>
这是我的 PHP 代码
<?php
$chatLog = fopen("chatLog.txt","a+") or die("Eror loading chat... Please try again later");
$chat = htmlspecialchars($_POST['message']);
fwrite($chatLog, $chat . "<br>");
fclose($chatLog);
?>
这是我的控制台中出现的内容
(index):85 chat updated
(index):72 Sending message to server
(index):85 chat updated
(index):81 Message sent to server
最佳答案
尝试使用
success: update
代替
success: update()
关于javascript - jQuery .ajax 在发送请求之前调用成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956592/