[英]JSON object properties are undefined
我從AJAX調用中獲取一個JSON對象並記錄結果如下:
console.log(response);
這是控制台中記錄的響應:
{"filename":"new.jpg","orientation":"vertical"}
但是,當我
console.log(response.orientation);
我得到一個未定義的回復。
我讀過的大多數答案都表明返回了一個數組而不是一個對象而且響應[0] .orientation應該可以工作,但這不是這里的情況。 當我將相同的數組分配給控制台中的另一個變量時:
var obj = {"filename":"new.jpg","orientation":"vertical"}
然后obj.orientation返回正確的值。
我在PHP中創建JSON對象:
$response=array('filename' => $newfilename, 'orientation' => $orientation);
$response=json_encode($response);
echo $response;
顯然為什么屬性顯示未定義?
要么:
header("Content-type: application/jason");
在PHP中,在JavaScript中的AJAX調用中指定dataType: "json"
,或者調用JSON.parse
。
您將需要解析您的字符串以獲取正確的JSON對象。 JSON.parse(響應); 將為您提供一個JSON對象,您可以從中讀取屬性
你可以在jsfiddle中嘗試以下示例嗎?
這不是使用JSON.parse()的更好方法; 或$ .parseJSON(); (jquery版)
但是,如果這是你的問題,json作為字符串返回,這將修復它,你可以改變你的代碼
我認為ajax / php部分應該看起來像Ajax
$.ajax({
type: "POST",
url: "link.php",
dataType: "json",
success: function(result){
alert(result.orientation);
}
});
PHP
$response=array("filename" => "$newfilename", "orientation" => "$orientation");
$response=json_encode($response);
echo $response;
確保使用至少5.2 php版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.