ajax响应上的JSON对象不可用

时间:2013-12-23 09:13:02

标签: javascript ajax json

我有一个来自AJAX请求的JSON对象。

当我做console.log(响应);我在控制台中看到了我的对象。但是,如果我console.log(response.mostSearched); undefined,我会得到var obj = {...etc};,为什么?

我从devTools控制台复制了该对象并输入了像console.log(obj.mostSearched);这样的javascript,然后我做了console.log(response);,这很有效。

我错过了什么,为什么不从 var req = new Request({ method: 'post', url: stats_ajax_cal, data: { 'itemSelect': itemSelect, 'type_of_graph': type_of_graph, 'dateFrom': dateFrom, 'dateTo': dateTo, }, onSuccess: function(response) { console.log(response); // looks good var obj = response; console.log('***'); console.log(obj); // looks good console.log(obj.mostSearched); // undefined } }).send();

我的Ajax请求:

{
    "mostSearched": {
        "title": "Most serached houses",
        "colNames": [],
        "rowNames": {
            "21": 1,
            "10": 2,
            "76": 1,
            "20": 1,
            "23": 1,
            "13": 3,
            "18": 1
        }
    },
    "timeOfDay": "",
    "averagePrice": 5904.8,
    "averageDuration": 0.6,
    "searchedDays": {
        "2013-12-21": 1,
        "2013-12-22": 1,
        "2013-12-23": 1,
        "2013-12-24": 1,
        "2013-12-25": 1,
        "2013-12-26": 1,
        "2013-12-27": 1,
        "2013-11-16": 2,
        "2013-11-17": 2,
        "2013-11-18": 2,
        "2013-11-19": 2,
        "2013-11-20": 2,
        "2013-11-21": 2,
        "2013-11-22": 2,
        "2013-11-23": 2,
        "2013-11-24": 2,
        "2013-11-25": 2,
        "2013-11-26": 2,
        "2013-11-27": 2,
        "2013-11-28": 2,
        "2013-11-29": 2,
        "2013-09-06": 4,
        "2013-09-07": 4,
        "2013-09-08": 4,
        "2013-09-09": 4,
        "2013-09-10": 4,
        "2013-09-11": 4,
        "2013-09-12": 1,
        "2013-10-07": 3,
        "2013-10-08": 3,
        "2013-10-09": 3,
        "2013-10-10": 3,
        "2013-10-11": 3,
        "2013-10-12": 3
    }
}

我的对象:

{{1}}

1 个答案:

答案 0 :(得分:1)

您需要使用JSON.parse解析响应字符串:

var obj = JSON.parse(response);