javascript - 通过 jQuery AJAX 设置和获取 PHP 变量

标签 javascript php jquery ajax chat

我正在尝试为自己和 friend 制作一个基本的聊天系统。这很简单,但是,ajax 让我非常困惑。我使用ajax请求一个php页面,我在其中设置了用户名,以及上次下载的聊天记录。但是,我不知道如何读取 php 页面的回显内容。我在网上查了一下,但有很多变化,这让我更加困惑。谁能给我一些指导吗?

Scripts.js(已链接 jQuery)

// on document ready + called every second

 $.ajax({
            url: 'download.php',
            type: 'REQUEST',
            datatype: 'json',
            data: ({
                last_downloaded: latestTimestamp,
                username: username
            }),
            success: function (data) {
                console.log(data.message[0].time);
                // Uncaught TypeError: Cannot read property '0' of undefined 
                // how do I get the time from the json?
                // {"message":{"chat":"Hello, world!","time":"2014-05-09 17:32:00,"username":"Josue"},"message":{"chat":"This is my second message.","time":"2014-05-09 17:32:05,"username":"Josue"}}

            }
        });

            latestTimestamp = data.message[0].time;
            downloadingTimer = setTimeout(actuate, timeoutValues[currentTimeoutIndex]);

    }

下载.php

这是我的 php 页面作为普通字符串回显的内容(现在格式正确的 JSON):

[
   {
      "chat":"Hello, world!",
      "time":"2014-05-09 17:32:00",
       "username":"Josue"
   },
   {
      "chat":"This is my second message.",
      "time":"2014-05-09 17:32:05",
      "username":"Josue"
   }
]

我的页面顶部有 header("Content-Type: application/json"); 。我做错了什么吗?

最佳答案

您的 JSON 响应格式不正确。日期戳后面的逗号位于引号内,而不是在引号外:

      "time":"2014-05-09 17:32:00,"      username":"Josue"
   },

此外,您应该使用方括号来表示消息数组。您的 JSON 应如下所示:

{ "message": [
   {
      "chat":"Hello, world!",
      "time":"2014-05-09 17:32:00",
       "username":"Josue"
   },
   {
      "chat":"This is my second message.",
      "time":"2014-05-09 17:32:05",
      "username":"Josue"
   }
]
}

您可以使用json_encode()将 PHP 数组或对象转换为 JSON 字符串的函数:

<?php
    $my_arr = array("message" => array());
    $my_arr["message"][] = array("chat" => "Hello, World!", "time" => "2014-05-09 17:32:05", "username" => "Josue");

    echo json_encode($my_arr);
?>

关于javascript - 通过 jQuery AJAX 设置和获取 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575506/

相关文章:

javascript - 循环遍历表并将特定单元格存储在数组中(如果选中行)

php - 尝试将数据输入mysql时出现几个错误

php - Laravel,sync() - 如何同步数组并传递额外的数据透视字段?

javascript - 如何在javascript中读取php对象关系(自定义属性)

jquery - 如何将此 jquery 菜单移动到我想要的位置?

php - Jquery onclick,使父Div不可见

javascript - 如何在 Django 模板中连接内容 block ?

javascript - 如何解决错误 : "undefined is null or not object ie in ext js" in IE?

javascript - 在 AngularJS 中将对象推送到 $scope.array 与 var x = [ ] 时是否存在性能问题?

javascript - 在 Javascript 中使用 document.domain 的同源策略解决方法