开发者

help needed with json_encode($array) problem please

开发者 https://www.devze.com 2023-04-01 00:10 出处:网络
i have this code: 开发者_运维知识库 <script> $(document).ready(function() { refresh(); }); function refresh()

i have this code: 开发者_运维知识库

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

    function refresh()
    {      
        $.get('getMessageDetails.php', function (json) {
            alert(json);  //as a test for now
        });
    }
</script>

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

?>

and my html:

echo "<tr>";
echo '<td><a id = "message_id" class="red_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'"><span id = "subject">'.$r['subject'].'</span></a></td>';
echo '<td id = "unique_code1">'.$uniqueCode1.'<span id = "unique_code2" class="pink_text">'.$uniqueCode2.'</span><span id = "unique_code3">'.$uniqueCode3.'</span></td>';
echo "</tr>";

how come when i alert(json) i get the values im supposed to get which is the last message:

[{"subject":"Freechat ha ha","id":"15","created_at":"2011-08-29 11:16:45","unique_code":"LUCINEM000RC","opened_once":"0"}]

BUT as soon as i code this:

alert($("#subject").html(json.subject));  
alert($("#message_id").html(json.id));
alert($("#unique_code1").html(json.unique_code));

i get the first message's details??? which is not what i want where am i going wrong please?? thank you


Try this:

alert(json[0].subject);

since the json string is wrapped in [] it forms an array from which you want to get the first element


in JSON

  • object are denoted by {}
  • array are denoted by []

so to access the requred data, you need to do so..

alert(json[0].subject);
alert('<br>'+json[0].id);
alert('<br>'+json[0].created_at);
alert('<br>'+json[0].unique_code);
alert('<br>'+json[0].opened_once);

DEMO

UPDATE

actually there is problem in ur jquery function

either use jQuery.getJSON()

or if you are using jQuery.get then write "json" as an third argument like this

function refresh()
    {      
        $.get('getMessageDetails.php', function (json) {               
        },"json"); // <---here
    }

NOTE: why don't you install firebug, that will tell your error runtime

0

精彩评论

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