dongpaozhi5734 2017-12-21 18:53
浏览 125
已采纳

如何在$ .ajax方法的success属性中访问对象的元素?

function getReportedInfo(id) {
    $.ajax({
        url: 'includes/get_data.php',
        type: 'POST',
        data: {id:id},
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });
};

The JSON object returned from the get_data.php script is:

{
    id: 5, 
    username: "Anthony", 
    status: "accupied"
}

I am able to the length of the data object if I do console.log(data.length). However, I can see the object when I console.log(data) in the success property. I am not able to access the elements of the data obejct if I do console.log(data.username), doing this displays undefined in the console. I created a variable, data1, outside the scope of the function getReportedInfo and assigned the data retrieved via the success property to this variable after I tried to display the constents of data1 outside the function.

  • 写回答

2条回答 默认 最新

  • doyrte8419 2017-12-21 18:57
    关注

    Sounds like data is a string not an object. You can convert this to an object by using JSON.parse. Try the following code.

    function getReportedInfo(id) {
        $.ajax({
            url: 'includes/get_data.php',
            type: 'POST',
            data: {id:id},
            dataType: 'json',
            success: function(data) {
                var dataObject = JSON.parse(data);
                console.log(dataObject.username);
            }
        });
    };
    

    Edit

    After discussing with OP in comments below, it was determined the object returned data was in a structure like the following, and is already in an object form (not a string)

    {
        "0": {
            id: 5, 
            username: "Anthony", 
            status: "accupied"
        }
    }
    

    Therefor the following code should work.

    function getReportedInfo(id) {
        $.ajax({
            url: 'includes/get_data.php',
            type: 'POST',
            data: {id:id},
            dataType: 'json',
            success: function(data) {
                console.log(data["0"].username);
            }
        });
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记