简体   繁体   English

JSON.parse意外字符

[英]JSON.parse Unexpected character

I have a JSON object stored in a mongoDB collection. 我在mongoDB集合中存储了一个JSON对象。 The object represents the positions of 5 x images, 5 y images, and a tictactoe board image. 该对象表示5 x图像,5 y图像和针孔板图像的位置。

On an interval, I send a request to a php file that responds with this object, and then I want to parse that object and move the pieces accordingly. 每隔一段时间,我向该对象响应的php文件发送一个请求,然后我想解析该对象并相应地移动各个部分。

this is my request: 这是我的要求:

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

but I get: JSON.parse: unexpected character 但我得到:JSON.parse:意外字符

When I console.log data firebug gives me the right object so I know it's returning properly. 当我console.log数据firebug给我正确的对象,所以我知道它正在正确返回。

In e4.php: 在e4.php中:

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

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

$conn->close();

print $doc['world'];

where conn is the connection, and collection is the collection I'm working in. 其中conn是连接,而collection是我正在使用的集合。

The database is updated in e3.php: 数据库在e3.php中更新:

$encodedworld = $_REQUEST['data'];

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

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

$doc['world'] = $encodedworld;

$collection->save($doc);

$conn->close();

print $encodedworld;

Any ideas? 有任何想法吗? I'm stumped 我很困惑

Thanks in advance. 提前致谢。

jQuery's getJSON deserializes the JSON for you, so data will be an object graph, not a string. jQuery的getJSON为您反序列化JSON,因此data将是对象图,而不是字符串。 From the documentation: 从文档中:

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. success回调将传递返回的数据,该数据通常是由JSON结构定义并使用$.parseJSON()方法进行解析的JavaScript对象或数组。

So since data has already been deserialized, you don't want or need to call JSON.parse on it. 因此,由于data 已经反序列化,因此您不需要或不需要对其调用JSON.parse Doing so will implicitly call toString on data , which will return either [object Object] or [object Array] , hence JSON.parse not liking it as input. 这样做将隐式调用data toString ,这将返回[object Object][object Array] ,因此JSON.parse不喜欢将其作为输入。 :-) Just use data directly: :-)只需直接使用data

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

Separately: Unless you declared world somewhere you didn't show, your code was also falling prey to The Horror of Implicit Globals . 另外:除非您声明未显示的world否则您的代码也将成为“隐式全球恐怖”的猎物。 You probably wanted to have var in there. 您可能想在那里var But with the change above, you don't need the variable at all, so... 但是有了上面的更改,您根本不需要该变量,所以...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM