jquery – 为什么要提醒(json [0] .subject);给undefined?

我有这个代码:

 <script>
    $(document).ready(function()
    {
        refresh();
    });

    function refresh()
    {      
        $.get('getMessageDetails.php', function (json) {
            alert(json);
            alert(json[0].subject);
        },"json");
        window.setTimeout(refresh,30000);
    }   
</script>

然后我有getMessageDetails.php:

<?php
//header('Content-Type: application/json; charset=utf-8');
include('header_application.php');
$lastNewMessageCnt = $obj_clean->getUnopenedMessagesCount($_SESSION['user_id']) + 1;
$last_unopened_message_row = $obj_clean->getLastUnopenedMessage($_SESSION['user_id'],$lastNewMessageCnt); 
echo json_encode($last_unopened_message_row); 
?>

然后我有警报(json),显示:

[{"subject":"Freechat ddd","id":"19","created_at":"2011-08-29 14:58:27","unique_code":"ALLEYCA000RC","opened_once":"0"}] 

哪个是对的

但警告(json [0] .subject);给undefined ???

请帮忙?
谢谢

最佳答案 如果您的第一个警报显示您所说的内容,那么您的json变量的内容不会被视为json – 如果您在警报中看到[object Object].检查
here.

所以你需要指定返回的是json(你做的);但是你也应该确保PHP发送正确的响应头.在发送输出之前添加下面的第一行:

header('Content-type: application/json');
echo json_encode($last_unopened_message_row); 
点赞