【问题标题】:Issue in accessing object property in javascript shows undefined? [duplicate]在 javascript 中访问对象属性的问题显示未定义? [复制]
【发布时间】:2017-03-02 07:32:01
【问题描述】:

我只是调用返回 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);
?> 

在控制台中响应数据

对象{电子邮件:“sameerdighe14@gmail.com”,类型:“google”}

【问题讨论】:

  • 请添加您的回复数据。
  • 当你已经在做(var attr in data)时,你真的需要这条线if (data.hasOwnProperty(attr))吗?
  • @brk 检查属性,如果有属性为空,则不会将其分配给其他对象。
  • 我添加了响应数据@lin

标签: javascript php angularjs


【解决方案1】:

您需要使用 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'}
    });
}

【讨论】:

  • 我还是有同样的问题。在控制台中打印 undefined
  • 哦对我有用。
  • 但仍然计数不起作用@lin
  • @SaMeE 算什么?
  • console.log(filteredData.count);本声明。
【解决方案2】:

代码未按您预期的顺序运行。 $http 需要时间运行,因此 apiCall 在修改之前返回响应。

要解决此问题,您需要使用 Promise 确保您的代码仅在您拥有所需的所有数据时运行。

此外,从$http 返回的数据有一个属性data,其中包含调用的结果。

function sendData(postData, url) {
  // subscribe to promise, and add your code in the then block
  apiCall(postData,url)
    .then(function(response) {
      console.log(response.email);
      console.log(response.count);
    });
}

function apiCall(postData, postUrl) {
  // return the promise
  return $http({
    method  : 'POST',
    url     : postUrl,
    data    : postData, 
    headers : {'Content-Type': 'application/json'}
  }).success(function(response) { 
    var result = {};
    for (var attr in response.data) {
      if (response.data.hasOwnProperty(attr)) {
        result[attr] = response.data[attr];
      }
    }  
    return result;   
  });
}

请注意,来自 $http 请求的data 属性保证是一个普通对象,其原型上没有额外属性,因此您实际上不需要hasOwnProperty 检查。 apiCall 可以简化:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2011-02-14
  • 2016-02-26
  • 1970-01-01
  • 2011-02-04
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多