jquery访问phpjason_encoded数组


jquery accessing php jason_encoded array

在test.php中:

<?php
array_push($stack, "BLABLA");
array_push($stack, "BLABLA2");
echo json_encode($stack);
?>

在test.html中:

<script type="text/javascript">
$(document).ready(function(){
    $.post( 
    'test.php', // location of your php script
    {}, // any data you want to send to the script
    function( data ){  // a function to deal with the returned information
        $('#mydiv').html(data[0]).show();
    }, "json");
});
</script>
<div id="mydiv"></div>

我已经做了一些健全性检查,似乎data[0]不是访问我在php中推送的第一个元素的正确方式。那么我该怎么做呢?

尝试

<?php
    $stack = array();
    array_push($stack, "BLABLA");
    array_push($stack, "BLABLA2");
    echo json_encode($stack);
?>

看看它肯定会在id为mydiv的div中给你BLABLA

只需先将$stack定义为空数组,或者确保$stack数组已经存在。

使用firebugFirefox插件。

将数据转换回数组:

function( data ){  // a function to deal with the returned information
    data = JSON.parse(data); // convert the JSON data back to an array
    $('#mydiv').html(data[0]).show();
}, "json");