JSON对象属性未定义
我从一个AJAX调用得到一个JSON对象返回和记录这样的结果: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.parse(或jQuery中的$ .parseJSON)做了诀窍。我不知道为什么它不在我阅读的几个教程中...谢谢! –
似乎是一个常见问题,几乎没有一天,我们没有看到有人提出基本相同的问题。 – Barmar
您将需要解析您的字符串以获取适当的JSON对象。 JSON.parse(response); 将为您提供一个JSON对象,从中可以读出的属性
你可以在jsfiddle中尝试下面的例子。
这不是更好的方式,您可以使用JSON.parse();或$ .parseJSON(); (jQuery的版本)
但如果这是你的问题,要返回的JSON作为一个字符串,这个修复它,你可以改变你的代码
$。parseJSON完美工作。谢谢! –
我认为AJAX/PHP的一部分应该看起来像 阿贾克斯
$.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版本
如果您的响应是一个字符串,您必须通过'JSON.parse'传递它,然后才能访问属性。另外,[没有这样的东西作为JSON对象](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – jbabey
你可以发布你的代码如何你发送ajax请求和成功函数 – Ashirvad