php - 简单的php ajax聊天

标签 php json jquery fwrite fread

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

这是 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>

最佳答案

可能是你的 $chat 变量

$chat = json_decode($data);

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

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

名称和消息是值,字段名称是名称和消息。

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

关于php - 简单的php ajax聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19564398/

相关文章:

json - Chrome DevTools Timeline .json 中的时间戳

jquery - fancybox 中的箭头定位

php - 帮助获取传递到 Jquery 自动完成插件的正确信息以获得可点击的结果

php - Heroku 连接到 RDS MySQL 时出现连接超时错误

javascript - 为什么我无法通过 CURL PHP 获取包含实际内容的链接,而不是手动访问它?

php - 在数据表 php 中获取复选框字段时出现问题

javascript - 在更改选择下拉列表中的值时更新引导日期选择器的 DaysOfWeekDisabled

PHP & MySQL 循环问题

mysql - 如何在 javascript (nodejs) 中使用 for 或 foreach 将带有对象值的数组插入到 mysql 中?

json - 将 Json 响应中的对象列表映射到 flutter 中的列表