在json对象上显示子项

时间:2015-03-06 18:26:45

标签: php jquery json

我有一个php文件,返回这个json(我已经验证了它):

{"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]} 

在jquery中,如何返回'图像的子女数量?当我使用:

$.post('php/file.php', {variable: variable}, function(returnedData) {
        console.log(returnedData);
        var obj = jQuery.parseJSON( returnedData );
        console.log(obj.images.length);

    });

我得到了#undefined'。

这是我在php中构建json的方式吗?

 $variable= $_POST['variable'];
$imgdir    = '../' . $variable. '/img';
$weeds = array('.', '..'); 
$images = array_diff(scandir($imgdir), $weeds); 
$viddir = '../' . $school . "/vid";
$vids = array_diff(scandir($viddir), $weeds); 
$data = array();
$data['images'] = $images;
$data['videos'] = $vids;
echo json_encode($data);

2 个答案:

答案 0 :(得分:1)

这是因为obj.images不是Array,你可以这样length



var returnedData = {"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]};

console.log(Object.keys(returnedData.images).length);




  

Object.keys() - 返回给定对象的数组   可枚举的属性

或者您可以使用for..in,就像这样



 var returnedData = {"images":{"2":"building.jpg","3":"campus.jpg","4":"grads.jpg","5":"trio.jpg"},"videos":[]};

var count = 0;
for (var i in returnedData.images) {
  if (returnedData.images.hasOwnProperty(i)) {
     count += 1;  
  }
}

console.log(count);




答案 1 :(得分:0)

为什么不使用$ .getJSON():

$.getJSON('php/file.php', {variable: variable}, function(returnedData) {
    console.log(returnedData);
    console.log(Object.keys(returnedData.images).length);
});