jQuery .ajax在发送请求之前调用成功函数

时间:2015-01-15 03:58:25

标签: javascript php jquery html ajax

我正在尝试为我的网站制作一个聊天框。基本上,用户使用id chat-input将聊天内容键入textarea。当用户单击Enter按钮时,它会调用sendChat()功能。此函数将请求发送到服务器上的php文件,该文件将用户的聊天添加到chatlog (服务器上的文本文件)。成功时,javascript应该调用update()函数,该函数对服务器上的chatlog.txt文件执行get请求,并将其加载到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

2 个答案:

答案 0 :(得分:5)

尝试使用

success: update

而不是

success: update()

答案 1 :(得分:0)

像这样更改你的ajax

$.ajax({
                    type: "POST",
                    async: "false",
                    url: "chatResponse.php",
                    data: datavar,
                    success:function(){ update()}
                });
相关问题