ajax在尝试访问d [obj] .src时返回undefined

时间:2015-09-28 03:55:14

标签: javascript php jquery ajax

AJAX

  function ajax_json_gallery(folder) {
      alert(folder);
      var thumbnailbox = $('#thumbnailbox');
      $.ajax({
          type: "POST",
          url: "json_gallery_data.php",
          contentType: "application/x-www-form-urlencoded",
          dataType: "json",
          data: "folder=" + folder,
          success: function(d) {
              for (var obj in d) {
                  if (d.hasOwnProperty(obj)) {
                      alert(d[obj]); //access data// 
                      alert(d[obj].src); //undefined//
                  }
              }
          }
      });
  }

PHP

header('Content-Type: application/json');
$folder = "Img/Company1/Jersey1";
$dir = $folder."/";
$dirHandle = opendir($dir); 
$i = 0;
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
    if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
        $i++;
        $src = "$dir$file";
$directoryfiles[] = '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
    }
}
closedir($dirHandle);

echo json_encode($directoryfiles);

的console.log(d)

[""img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },", 
    ""img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },", 
    ""img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },", 
    ""img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" },"]

X3

我正在使用ajax获取文件夹目录中的所有图像,并返回到ajax但是当我尝试访问d [o] .src时它返回undefined,我不知道我在这里缺少什么。

2 个答案:

答案 0 :(得分:2)

不要尝试自己编写JSON文本。只需创建一个关联数组或stdClass对象,添加适当的键/值,然后将其添加到$directoryfiles。然后,json_encode将执行正确的编码

$directoryfiles = array();
while ($file = readdir($dirHandle)) {
    if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
        $i++;
        $src = "$dir$file";
        $temp = new stdClass;
        $temp->num = $i;
        $temp->src = $src;
        $temp->name = $file;
        $directoryfiles["img".$i] = $temp;
    }
}
closedir($dirHandle);

echo json_encode($directoryfile);

答案 1 :(得分:0)

将json的格式更改为,

{"img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" }, 
 "img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" }, 
 "img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" }, 
 "img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" }};

然后你使用代码,

console.log(d.img1.src);