【问题标题】:jQuery .ajax calls success function before sending requestjQuery .ajax 在发送请求之前调用成功函数
【发布时间】: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


【解决方案1】:

尝试使用

success: update

而不是

success: update()

【讨论】:

  • 有什么理由可以这样做吗?是不是因为函数自动调用了数据和状态参数?
  • @KenthMirta 有点晚了,但是是的,这个解决方案比公认的答案更优雅。您可以将success 想象为函数的变量,但update() 是对函数update调用update 本身就是您要传递给该方法的函数。
  • @KenthMirta 所以接受的答案将匿名函数传递给success参数,然后调用update函数,而这个答案直接传递更新函数。当你传递这行代码时,像update() 这样的函数call 会执行该函数。
【解决方案2】:

像这样改变你的ajax

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多