gpt4 book ai didi

javascript - 在 javascript 中访问对象属性时出现问题显示未定义?

转载 作者:行者123 更新时间:2023-11-28 04:56:00 26 4
gpt4 key购买 nike

我只是调用返回 josn 编码数据的 api 并尝试打印对象属性,但显示未定义,但是当我打印该对象时,该对象具有该属性和值。

我的代码

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);
?>

控制台中的响应数据

Object {email: "sameerdighe14@gmail.com", type: "google"}

最佳答案

您需要使用 promise 才能使其发挥作用。一旦 HTTP 请求成功完成,您的 success 函数就会被异步调用。这样,return response; 会在请求完成之前执行 -> 因此它仍然是一个空对象 {}。使用AngularJS promises使其发挥作用。这是一个简单的工作fiddle example .

function sendData(postData, url){

var filteredData = {};

apiCall(postData,url).then(function (response) {

for (var attr in response.data) {
if (response.data.hasOwnProperty(attr)) {
filteredData[attr] = response.data[attr];
}
}

console.log(filteredData.email);
console.log(filteredData.count);
});
}


function apiCall(postData, postUrl){
return $http({
method : 'POST',
url : postUrl,
data : postData,
headers : {'Content-Type': 'application/json'}
});
}

关于javascript - 在 javascript 中访问对象属性时出现问题显示未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42549284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com