gpt4 book ai didi

javascript - JSON.parse 意外字符

转载 作者:行者123 更新时间:2023-11-28 12:37:29 24 4
gpt4 key购买 nike

我有一个 JSON 对象存储在 mongoDB 集合中。该对象代表 5 x 图像、5 y 图像和井字游戏板图像的位置。

每隔一段时间,我向一个 php 文件发送一个请求,该文件用该对象进行响应,然后我想解析该对象并相应地移动各个部分。

这是我的要求:

$.getJSON
(
"e4.php",
"",
function(data)
{
world = JSON.parse(data);
moveObjects(world);
}
);

但我得到:JSON.parse:意外字符

当我console.log数据firebug给我正确的对象时,我知道它正确返回。

在 e4.php 中:

$criteria = array("name" => "world");

$doc = $collection->findOne($criteria);

$conn->close();

print $doc['world'];

其中 conn 是连接,collection 是我正在使用的集合。

数据库在 e3.php 中更新:

$encodedworld = $_REQUEST['data'];

$criteria = array("name" => "world");

$doc = $collection->findOne($criteria);

$doc['world'] = $encodedworld;

$collection->save($doc);

$conn->close();

print $encodedworld;

有什么想法吗?我被难住了

提前致谢。

最佳答案

jQuery 的 getJSON为您反序列化 JSON,因此 data 将是对象图,而不是字符串。来自文档:

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

因此,由于data已经已经被反序列化,您不希望或不需要对其调用JSON.parse。这样做将隐式调用 data 上的 toString,这将返回 [object Object][object Array] ,因此 JSON.parse 不喜欢将其作为输入。 :-) 只需直接使用 data 即可:

$.getJSON
(
"e4.php",
"",
function(world) // <=== Changed name of argument
{
moveObjects(world); // <=== Used it directly
}
);
<小时/>

另外:除非您在未显示的地方声明了 world,否则您的代码也会成为 The Horror of Implicit Globals 的牺牲品。 。您可能希望其中有 var 。但是通过上面的更改,您根本不需要该变量,所以...

关于javascript - JSON.parse 意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15648231/

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