传递给php的路径返回undefined

时间:2015-12-19 00:37:31

标签: javascript php

我正在尝试将路径传递给php脚本,然后脚本应该返回数组中该路径中的所有图像文件但是我不断得到的是未定义的错误,有人可以帮忙。

function LoadGallery(dir_path) {
  $.ajax({
    type: 'POST',
    url: "getimages.php",
    traditional: true,
    data:{ path : dir_path},
    type: "json",
    success: function(data){
        alert(data[0]);
    //    $("#image-container").val(data[0]);

    }
  });
}

PHP SCRIPT getimages:

<?php
if(isset($_POST['path'])){
    $dir = $_POST['path'];
    $img = array();

    if (is_dir($dir)) {
       if ($hnd = opendir($dir)) {
           while (false !== ($file = readdir($hnd))) {
               if ($file != "." && $file != "..") {
                    $img[] = $file;
                }
           }
           closedir($hnd);
        }
    }
    return $img;
 }
 ?>

1 个答案:

答案 0 :(得分:1)

更改您的PHP代码以返回带有结果的json。

<?php
if(isset($_POST['path'])){
    $dir = $_POST['path'];
    $img = array();

    if (is_dir($dir)) {
       if ($hnd = opendir($dir)) {
           while (false !== ($file = readdir($hnd))) {
               if ($file != "." && $file != "..") {
                    $img[] = $file;
                }
           }
           closedir($hnd);
        }
    }
    echo json_encode($img);
 }
 ?>