【问题标题】:Simple php ajax chat简单的 php ajax 聊天
【发布时间】:2013-10-24 11:15:13
【问题描述】:

我正在尝试做一个简单的 php 聊天应用程序,它通过 ajax 从客户端接收数据并将该数据写入文本文件进行存储。但是我在解析 json 后尝试获取“名称”和“消息”的行上不断收到未定义的索引错误。

这是 chat.php 文件:

<?php
    if (isset($_POST['data']))
    {        
        $data = $_POST['data'];
        $chat = json_decode($data);
        $name = $chat->name;
        $msg = $chat->msg;

        $file = "chat.txt";
        $fh = fopen($file, 'w') or die("Sorry, could not open the file.");

        if (fwrite($fh, $name + ":" + $msg))
        {
            $response = json_encode(array('exists' => true));
        } else {
            $response = json_encode(array('exists' => false));
        }
        fclose($fh);
        echo "<script type='text/javascript'>alert ('" + $name + $msg + "')</script>"
    }
?>

这是javascript:

<script type="text/javascript">
            $(document).ready(function() {
                $("#btnPost").click(function() {
                    var msg = $("#chat-input").val();
                    if (msg.length == 0)
                    {
                        alert ("Enter a message first!");
                        return;
                    }
                    var name = $("#name-input").val();
                    var chat = $(".chat-box").html();
                    $(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");

                    var data = {
                        Name : name,
                        Message : msg
                    };
                    $.ajax({
                        type: "POST",
                        url: "chat.php",
                        data: {
                            data: JSON.stringify(data)
                        },
                        dataType: "json",
                        success: function(response) {
                            // display chat data stored in text file 
                        }
                    });
                });
            });
        </script>

【问题讨论】:

  • 连接应该在 PHP 中使用 . 而不是 +
  • 是的,谢谢,我没有注意到 :D,我遇到的未定义索引的问题是因为我在数组中使用了不同的键。
  • 我现在重新编辑了帖子。

标签: php json jquery fwrite fread


【解决方案1】:

可能是你的 $chat 变量

$chat = json_decode($data);

不包含这些字段,但包含您在此处定义的名称和消息:

var data = {
  Name : name,
  Message : msg
}

name 和 msg 是 valuse,Field 名称是 Name 和 Message。

请尝试 print_r($chat) 看看它包含什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2011-07-12
    • 2017-09-10
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多