开发者

php multidimensional array into jQuery

I have a php multidimensional array populated from a table using the following code:

<?php starts

$array = array();
$i = 0;

while($row = mysql_fetch_array($result))
{

$array[$i] = array("handle" => $row['handle'],"firstname" => $row['first_name'],"lastname" => $row['last_name']);
$i++;
}

echo json_encode(json_encode($array));

?> php ends

this is called by .post from jQuery and when I alert() the data returned I get the following output:

[
{"handle":"admin","firstname":"admin","lastname":"admin"},
{"handle":"ms","firstname":"ms","lastname":"ms"},
{"handle":"op","firstname":"op","lastname":"op"},
{"handle":"ui","firstname":"ui","lastname":"ui"}
]

the Jquery code I use to extract the php array is:

$.post("test1.php","",
            function(data){

                var obj = $.parseJSON(data);
                alert(obj);
                var obj2 = $.parseJSON(obj);
                alert(obj2);
                alert(obj2[1]);
                var result = eval(data);
                alert(result[0][0]);


    },"html");

alert(obj) 开发者_如何学编程gives me the output specified. alert(obj2) gives me:

[object Object],[object Object],[object Object],[object Object]

alert(obj2[1]) gives me:

[object Object]

How do I get at the data in this???


Your first

var obj = $.parseJSON(data);

Should be all you need. You can then access your objects like:

obj[0]['handle']
// or
obj[0].handle


'[object Object]' is the toString() of an Object, which is implicitly called when using alert() (which alerts strings only).

You need to use dot notation to access it, or console.log() to view the object (provided your browser has a competent console).


To view any object details in IE9 use - console.dir(obj)

Where as in Firefox, you can use - console.log(obj)

Remember, the details will be written in the console (present in Developer Tools in IE and Firebug in Firefox)

Using console statments you can view your object structure and then you can access any property of object using '.' dot operator.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜