Ken*_*rta 4 html javascript php ajax jquery
我正在尝试为我的网站制作一个聊天框.基本上,用户使用id chat-input将聊天内容键入textarea.当用户单击Enter按钮时,它会调用该sendChat()函数.此函数将请求发送到服务器上的php文件,该文件将用户的聊天添加到chatlog (服务器上的文本文件).成功时,javascript应该调用update()函数,该函数对服务器上的chatlog.txt文件执行get请求,并将其加载到id为prev-chats的div中.问题是javascript在服务器响应之前调用update(),因此在刷新页面之前不会更新prev-chats.我可以告诉这个因为
a)聊天在我刷新页面之前没有更新,并且
b) 在谷歌浏览器中,按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>
Run Code Online (Sandbox Code Playgroud)
这是我的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);
?>
Run Code Online (Sandbox Code Playgroud)
这是我的控制台中出现的内容
(index):85 chat updated
(index):72 Sending message to server
(index):85 chat updated
(index):81 Message sent to server
Run Code Online (Sandbox Code Playgroud)
尝试使用
success: update
Run Code Online (Sandbox Code Playgroud)
代替
success: update()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1044 次 |
| 最近记录: |