【发布时间】:2015-01-15 03:58:24
【问题描述】:
我正在尝试为我的网站制作一个聊天框。基本上,用户使用 id chat-input 将他们的聊天输入到 textarea 中。当用户单击 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
【问题讨论】:
标签: javascript php jquery html ajax