gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:39:45 24 4
gpt4 key购买 nike

我正在尝试为自己和 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com