Javascript 从Ajax调用Jquery访问数据

Javascript 从Ajax调用Jquery访问数据,javascript,jquery,jquery-ui-autocomplete,Javascript,Jquery,Jquery Ui Autocomplete,我正在使用jQueryUI自动完成 我遇到的问题是从api返回的数据 "{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__ma

我正在使用jQueryUI自动完成

我遇到的问题是从api返回的数据

"{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__max_score":1.0}}"
我已经通过在线解析器运行了它,它是有效的,但我不知道如何访问旁边有相应编号的城镇列表


任何帮助都将不胜感激

我可以通过以下方式访问城镇“名称”和编号:

var test = {
    "d": {
        "results": [],
        "facets": {
            "facet_counts": {
                "Town": {
                    "": 0,
                    "londonderry": 136914,
                    "london bridge": 1,
                    "london": 8983316,
                    "london colney": 1
                }
            }
        },
        "__solr_time": 3473457,
        "__ser_time": 1564,
        "__t_time": 1421,
        "__count": 9120232,
        "__max_score": 1
    }
}
for(var prop in test.d.facets.facet_counts.Town){
     console.log(prop);
     console.log(test.d.facets.facet_counts.Town[prop]);
}
只需在字符串上运行JSON.parse(),然后拉出
Town
节点

var string; // the data string returned by API.
var dataObj = JSON.parse(string);
var Town = dataObj.d.facets.facet_counts.Town;

// access the properties as needed
var londonCount = Town.london;
var londonBridgeCount = Town['london bridge']; // need to use bracket notation to get this one

阅读有关关联数组的内容。如果您不知道如何解构返回值,那么您是如何/为什么要这样格式化返回值的?我无法控制它,我永远不会这样做。谢谢,它工作得很好,但是当我从ajax调用中调用相同的代码时,它失败了$.ajax({url:'town.php',键入:'GET',缓存:false,成功:函数(text){alert(text);for(text.d.facets.facet_counts.town中的var prop){console.log(prop);//console.log(test.d.facets.facet_counts.town[prop])}}我将执行console.log以确保从ajax调用返回的文本的格式相同(即对象不是字符串)。实际上,您可能只需要执行:
for(text.facets.facet\u counts.Town中的var prop)
或者像Mike说的那样,在你去你需要的城镇之前做一个JSON.parse。不管怎样,console.log都会告诉你你需要知道的。谢谢你的帮助,我终于让它工作了。JSON.parse只是错误。success:function(dat,status){if(status==“success”)response($.map(dat.d.facets.facet_counts.Town,函数(项,键){if(项==0){return}return{label:key+”(“+item+”),value:key}}}}}}嘿@RobPaddock太棒了!如果一切顺利,如果您将此标记为答案,我将不胜感激:)