将数据数组从PHP返回到jQuery

时间:2015-04-07 16:23:32

标签: php jquery ajax post netbeans

为我孩子的bday建立一个网站,这将允许他的祖父母登录并点击过去两年每天的15gig图片/视频。但似乎无法从jQuery中的PHP程序中捕获任何数据。我一直收到一条错误,上面写着: “无法加载资源:net :: ERR_EMPTY_RESPONSE(03:27:54:409 |错误,网络在public_html / pics / desi / desiPics.php”。 我认为程序相对简单。我不知怎的过于复杂?

来自desiPics.php:

<?php
$dir= glob('pics/desi/{*.jpg,*jpeg,*png,*gif}', GLOB_BRACE);
echo json_encode($dir);
?>

来自jQuery:

var desiPics = [];
  $.ajax({
   type: 'POST',
   url: 'pics/desi/desiPics.php',
   cache: false,
   async: true,
   success: function(result){
       if(result){
           desiPics = eval(result);
           alert(desiPics.length);
       }else{
           alert('error');
       }
     }
 });

1 个答案:

答案 0 :(得分:0)

您必须解析返回到对象中的json,以便在您使用的方法中使用它。

success: function(result){
   result = JSON.parse(result);
   if(result){
       desiPics = result;
       alert(desiPics.length);
   }else{
       alert('error');
   }
 }

编辑:我添加了dataType“json”,它将结果转换为对象。

var desiPics = [];
  $.ajax({
   type: 'POST',
   url: 'pics/desi/desiPics.php',
   cache: false,
   async: true,
   dataType: "json",
   success: function(result){
   if(result){
       desiPics = result;
       alert(desiPics.length);
   }else{
       alert('error');
   }
 }
});