无法访问返回对象中的属性 [英] Can't access property in returned object

查看:128
本文介绍了无法访问返回对象中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我似乎无法查询返回的JSON,但是我可以打印出整个响应,这是我的JSON响应,只有在执行msgBox()提示符时才能看到此消息:

I've got a problem where I can't seem to query my JSON coming back, I can print out the entire response though, here's my JSON response, I can only see this when I do a msgBox() prompt:

{ "Addresses" : 
    "[{ 
        Building=Megatron Skyscraper,
        BuldingId=1998,
        AccountId=2000,
        Number=007,
        Name=Megatron 
        },{
        Building=StarScream Skyscraper,
        BuldingId=1999,
        AccountId=2001,
        Number=008,
        Name=StarScream
}]"}

这是我的代码:

function getReadyStateHandler(req)
{
    // Return an anonymous function that listens to the
    // XMLHttpRequest instance
    return function ()
    {
        // If the request's status is "complete"
        if (req.readyState == 4)
        {
            // Check that a successful server response was received
            if (req.status == 200)
            {
                msgBox("JSON Response recieved...");
                var addresses = req.responseText.toJSON();
                msgBox(req.responseText.toJSON());
            }
            else
            {
                // An HTTP problem has occurred
                alert("HTTP error: " + req.status);
            }
        }
    }
}

我已经尝试了addresses.Address[0].Cityaddressess.Addresses[0].City以及其他许多方面的所有内容-但这有点令人困惑!

I've tried everything from addresses.Address[0].City and addressess.Addresses[0].City and many others - but this is slightly confusing!

推荐答案

除了响应中没有City键之外,返回的对象仅包含一个(格式错误)字符串,不是对象数组.您可以使用 http://jsonlint.com

Apart from the fact that there's no City key in your response, your returned object contains only one (malformed) string, not an array of objects. You can check this using http://jsonlint.com

您是如何创建回复的?它看起来应该更像:

How did you create the response? It should look more like:

{ "Addresses" : [{ 
        "Building":"Megatron Skyscraper",
        "BuldingId":1998,
        "AccountId":2000,
        "Number":7,
        "Name":"Megatron"
        },{
        "Building":"StarScream Skyscraper",
        "BuldingId":1999,
        "AccountId":2001,
        "Number":8,
        "Name":"StarScream"
}]}

更新:"Number":007"Number":008中的那些前导零可能会引起问题,因为它们将被解释为八进制值.我已经将其删除了.

Update: those leading zeros in "Number":007 and "Number":008 may cause problems, because they will be interpreted as octal values. I've removed them in my answer.

这篇关于无法访问返回对象中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆