[英]JSON object properties are undefined
I'm getting a JSON object back from an AJAX call and logging the result like this: 我从AJAX调用中获取一个JSON对象并记录结果如下:
console.log(response);
And this is the response logged in the console: 这是控制台中记录的响应:
{"filename":"new.jpg","orientation":"vertical"}
However, when I 但是,当我
console.log(response.orientation);
I get a response that it is undefined. 我得到一个未定义的回复。
Most of the answers I've read indicate that an array was returned instead of an object and that response[0].orientation should work, but that is not the case here. 我读过的大多数答案都表明返回了一个数组而不是一个对象而且响应[0] .orientation应该可以工作,但这不是这里的情况。 When I assign the same array to another variable in the console: 当我将相同的数组分配给控制台中的另一个变量时:
var obj = {"filename":"new.jpg","orientation":"vertical"}
Then obj.orientation returns the correct value. 然后obj.orientation返回正确的值。
I'm creating the JSON object in PHP: 我在PHP中创建JSON对象:
$response=array('filename' => $newfilename, 'orientation' => $orientation);
$response=json_encode($response);
echo $response;
Is it apparent why the properties are showing undefined? 显然为什么属性显示未定义?
Either put: 要么:
header("Content-type: application/jason");
in the PHP, specify dataType: "json"
in the AJAX call in the JavaScript, or call JSON.parse
. 在PHP中,在JavaScript中的AJAX调用中指定dataType: "json"
,或者调用JSON.parse
。
You will need to parse your string to get a proper JSON object. 您将需要解析您的字符串以获取正确的JSON对象。 JSON.parse(response); JSON.parse(响应); will provide you with a JSON object from which you can read the properties 将为您提供一个JSON对象,您可以从中读取属性
Can you try the following example in jsfiddle. 你可以在jsfiddle中尝试以下示例吗?
This is not the better way you can use JSON.parse(); 这不是使用JSON.parse()的更好方法; or $.parseJSON(); 或$ .parseJSON(); (jquery version) (jquery版)
But if this is your problem, json being returned as a string this fix it and you can alter your code 但是,如果这是你的问题,json作为字符串返回,这将修复它,你可以改变你的代码
http://jsfiddle.net/dadviegas/gf8Yq/ http://jsfiddle.net/dadviegas/gf8Yq/
I think the ajax / php part should look like Ajax 我认为ajax / php部分应该看起来像Ajax
$.ajax({
type: "POST",
url: "link.php",
dataType: "json",
success: function(result){
alert(result.orientation);
}
});
PHP PHP
$response=array("filename" => "$newfilename", "orientation" => "$orientation");
$response=json_encode($response);
echo $response;
Make sure that use at least 5.2 php version 确保使用至少5.2 php版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.