我只是调用api返回josn编码数据并试图打印对象属性,但显示未定义,但是当我打印该对象时,该对象具有该属性和值。 “sameerdighe14 @ gmail的:在javascript中访问对象属性的问题显示未定义?
我的代码基于
function sendData(postData, url){
var response = apiCall(postData,url);
console.log(response.email)
console.log(response.count);
}
function apiCall(postData, postUrl){
var response = {};
$http({
method : 'POST',
url : postUrl,
data : postData,
headers : {'Content-Type': 'application/json'}
}).success(function(data) {
console.log(data)
for (var attr in data) {
if (data.hasOwnProperty(attr)) response[attr] = data[attr];
}
});
return response;
}
PHP API
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$response = array();
$response['email'] = $_POST['oauth']['email'];
$response['type'] = $_POST['oauth']['type'];
echo json_encode($response);
?>
控制台
对象{电子邮件响应数据。 com“,输入:”google“}
请添加您的回复数据。 – lin
当你已经在做'(var attr in data)'时,你真的需要这行'if(data.hasOwnProperty(attr))'吗? – brk
@brk它检查属性,如果有空字段的属性,那么它不会将它分配给其他对象。 – SaMeEr