jQuery显示来自PHP的数组(json编码)


jQuery show array from PHP (json encoded)

我试图用jQuery显示一个数组,但它没有显示我想要的任何内容:p

所以我在谷歌上坐了一个小时后问这里,仍然不知道自己做错了什么。。

我的阵列是这样的:

if (isset($_POST['imageID'])) { 
            $array = array();
            list($width, $height, $type, $attr) = getimagesize("../img/libary/".$_POST['imageID'].".JPG");
            $array["dimension"] = $width.' x '.$height;
            $array["filesize"] = formatBytes(filesize("../img/libary/".$_POST['imageID'].".jpg"),0);
            $array["extensions"] = strtoupper(pathinfo("../img/libary/".$_POST['imageID'].".jpg", PATHINFO_EXTENSION));
            $array["filename"] = $_database->query("SELECT * FROM imglibary WHERE imageID='".$_POST['imageID']."' LIMIT 1")->fetch_object()->name; 
            $array["fileurl"] = $_SERVER['DOCUMENT_ROOT'].'/img/libary/'.$_POST['imageID'].'.JPG';
            echo json_encode($array);
        }

和jQuery代码:

$.post("jQuery.post.php", {imageID: imageID}, "json").done(function(data) { 
 // What to do here to get it to work? 
  });

希望你们都有答案:(

错过显示来自"数据"的答案:

{"dimension": "210x214", "filesize", "214kb", "extensions", "JPG", "filename": "somefile.jpg", "fileurl": "/img/libary/40.JPG"}

使用$.parseJSON解析从服务器返回的数据,除非您从PHP页面发送application/json标头。

如果您想从PHP页面开始发送正确的JSON头,请将其添加到页面顶部,默认情况下它设置为text/html,这就是为什么需要解析数据:

header('Content-type: application/json');

然后,它就像console.log(data.dimension)一样简单,不需要任何解析。只要您将json设置为dataType,jQuery就会自动为您解析数据。

如果您不想/不能发送正确的标头,或者不确定它们是什么,请使用parseJSON()

parseJSON示例:

$.post("jQuery.post.php", {imageID: imageID}, "json").done(function(data) { 
   var d = $.parseJSON(data);
   console.log(d.dimension);
});