开发者

why does alert(json[0].subject); give undefined?

i have this code:

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

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

then i have 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); 
?>

then i have the alert(json) which shows:

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

which is correct

but alert(json[0].subject); gives undef开发者_如何转开发ined???

please help? thank you


You have to convert json variable to correct json format variable.

Currently its a string variable.

You have to use it following way :

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

    function refresh()
    {      
        $.get('getMessageDetails.php', function (json) {
            alert(json);  // this is a string variable.
            json = $.parseJSON(json);  //now json varible is in correct json format.
            alert(json.subject); //you can call it dirctly like a associative array. No need to include '[0]'.
        },"json");
        window.setTimeout(refresh,30000);
    }   
</script>


It seems your JSON is not getting parsed correctly. Try using getJSON instead.

$.getJSON('getMessageDetails.php', function (json) {
   alert(json);
   alert(json[0].subject);
});


If your first alert shows what you say it does, then the content of your json variable is not being treated as json - if it was you'd see [object Object] in the alert. Check here.

So you need to specify what is returned is json (which you do); but you should also make sure PHP is sending the correct response headers. Add the first line below, before you send output:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜