1

クライアントから ajax 経由でデータを受け取り、そのデータをテキスト ファイルに書き込んで保存する単純な php チャット アプリケーションを実行しようとしています。しかし、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>
4

1 に答える 1

3

おそらくあなたの $chat 変数

$chat = json_decode($data);

これらのフィールドは含まれていませんが、ここで宣言した名前とメッセージは含まれています。

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

name と msg は値で、フィールド名は Name と Message です。

print_r($chat) を実行して内容を確認してください。

于 2013-10-24T11:34:24.427 に答える