在什么情况下JSON编码的数组可以成为字符串?

时间:2013-07-30 14:06:30

标签: php jquery json

我有一些与此类似的PHP 5代码:

$result = myFunction(...);  // return false, or doit action
$reply = array();
if ($result) {
   $reply['doit'] =  $result;
   $reply['status'] = "a status html string";
} else {
   $reply['content'] = "Some html text";
   $reply['menu'] = "Some other html text";
   $reply['status'] = "a different status html string";
}
return $reply;

来电者包含片段

$reply = somefunction();
echo json_encode($reply);

然后将此回复发送到客户端,其中jquery将其传递给我的函数

function handleReply(reply) {
    if (reply.doit) {
        handle action
    }
    if (reply.content) document.getElementById('content').innerHTML=reply.content;
    if (reply.menu) document.getElementById('menu').innerHTML=reply.menu;
    if (reply.status) document.getElementById('status').innerHTML=reply.status;
}

我一直在努力的是,当执行if语句的doit分支时,($ result是一个字符串)jquery给我的回复是一个字符串。当获取内容/菜单/状态侧($ result为false)时,reply是一个对象。

我在数组中添加了第二个索引,结果相同。虽然所有字符串都是ASCII,但我尝试通过UTF8_encode传递它们。我已经改变了'doit'的名称。来自' action'的索引如果是在jquery中触发某些行为。

只是要清楚,答案是错误的(例如)。

"{"doit":"obj=session&act=show&ID=3","status":"<p>Nic: Ian<br\/>Reseller: Coachmaster.co.uk<br\/>Status: SysAdmin <\/p>"}"

这是一个字符串。我期待:

{"doit":"obj=session&act=show&ID=3","status":"<p>Nic: Ian<br\/>Reseller: Coachmaster.co.uk<br\/>Status: SysAdmin <\/p>"}

哪个是对象/数组。这也是我的日志记录显示为回显的内容。

我在windows 7下使用php5.4.3,在linux和nginx下使用Apache和php 5.3.10,结果相同。 jquery是两个版本v1.7.2。还加载了jQuery UI - v1.10.3 - 2013-07-02。

如果它是jquery中的一个bug,它是一个非常奇怪的bug。我怎样才能证明这一点?

4 个答案:

答案 0 :(得分:4)

我认为你依赖于jQuery自动检测。尝试:

header('Content-Type: application/json');

答案 1 :(得分:0)

将字符串转换为JavaScript后,您必须eval()将其转换为JSON对象:

var reply_json = eval( reply );

然后,您可以访问reply_json.contentreply_json.menu,依此类推。

显然要小心你正在评估它是什么,确保它来自可信赖的来源等等。

答案 2 :(得分:0)

也许你可以试试:

jQuery.parseJSON()

答案 3 :(得分:0)

您使用$.getJSON() jquery方法还是$.ajax()

使用$.ajax()方法时,如果在进行ajax请求时没有指定dataType: "json"选项,jQuery将使用“智能猜测”(通过搜索响应MIME类型)来计算如何解释服务器响应(xml,html,plain,json对象......)。如果它无法自动计算,它将假定响应是纯文本,并且将在成功句柄中返回常规字符串。

您应该使用$.getJSON()或指定dataType: "json"

$.ajax({
    url: "....",
    dataType: "json",
    success: function(reply) { // success handle
        // if not specifying dataType: "json",
        // and if not using response headers to specify MIME type "application/json", 
        // reply will not be object but a string!
    }
});

或者,正如Marek在他的回答中所说,在响应头中指定MIME类型。