【问题标题】:Cannot target the JSON object without undefined result无法定位没有未定义结果的 JSON 对象
【发布时间】:2018-04-12 01:39:13
【问题描述】:

我有通过 ajax 提取的 JSON 编码数据,我正在尝试通过 jQuery 访问数据并填充一些字段,但是由于某种原因,我不断收到错误 data.entry_data is undefined

JSON 数据结构:

{
   "activity_counts":null,
   "config":{
      "csrf_token":"56gdf75fd6756g7",
      "viewer":null
   },
   "supports_es6":false,
   "country_code":"NL",
   "language_code":"en",
   "locale":"en_US",
   "entry_data":{
      "ProfileData":[
         {
            "logging_page_id":"profilePage_2321",
            "show_suggested_profiles":false,
            "userspecific":{
               "user":{
                  "full_name":"John Doe",
                  "username":"JohnDoe1",
                  "country":"United States"
               }
            }
         }
      ]
   }
}

我的 jQuery 代码:

$.ajax({
    type: "POST",
    url: "engine.php",
    data: $("#profile-info-form").serialize(),
    dataType: 'json',
    success: function(data){
        $profile_full_name = data.entry_data.ProfileData.userspecific.user.full_name;
        $profile_country = data.entry_data.ProfileData.userspecific.user.country;
        $profile_username = data.entry_data.ProfileData.userspecific.user.username;
    },
    error: function(){
        profileError();
    }
});

我也尝试使用data[0],例如$profile_full_name = data[0].entry_data.ProfileData.userspecific.user.full_name;,但没有成功,因为它显示相同的未定义错误。

我这几天一直在琢磨我在定位 JSON 对象时做错了什么,非常感谢任何帮助。

【问题讨论】:

    标签: jquery json ajax object


    【解决方案1】:

    如果成功回调返回的数据确实是上面粘贴的JSON结构,那么data.entry_data不应该是undefined。应该没有问题的。

    问题在于访问userspecific 属性,因为ProfileData 是一个数组。

    尝试更改此部分:data.entry_data.ProfileData.userspecificdata.entry_data.ProfileData[0].userspecific

    查看这个小提琴的例子:https://jsfiddle.net/mom5gw2q/7/

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 2012-03-16
      • 2018-06-07
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 2017-12-28
      相关资源
      最近更新 更多