2013-02-22 75 views
1

我正在使用Jquery Ui自动完成。从Ajax访问数据调用Jquery

我遇到的问题是从我的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}}" 

我已经通过在线分析器运行它,它是有效的,但我不知道如何与相应数量的访问旁边城镇的名单。

任何帮助,将不胜感激

+0

阅读关联数组。如果你不知道如何解构它,你如何/为什么要这样设置返回值? – Colleen 2013-02-22 23:45:14

+0

我无法控制,我永远不会这样做。 – 2013-02-23 17:46:45

回答

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]); 
} 
+0

由于它的工作原理是伟大的,但是当我从一个AJAX调用相同的代码调用失败 $阿贾克斯({ 网址:“town.php”, 类型:“GET”, 缓存:假的, 成功:text(text){ alert(text); for facet_counts.Town [prop]); } } – 2013-02-23 11:09:05

+0

我会做一个console.log以确保从ajax调用返回的文本格式相同(即一个对象不是字符串)。要做:'for(var prop in text.facets.facet_counts.T自己)'或者像迈克说的那样,在去你需要的城镇之前做一个JSON.parse。无论哪种方式,console.log会告诉你你需要知道什么 – 2013-02-23 15:15:20

+0

感谢您的帮助,我终于找到了工作。 Json.parse只是错误。 成功:函数(dat,状态)if(status ==“success”)response($。map(dat.d.facets.facet_counts.Town,function(item,key){ if(item == 0 ){ 回报 } 回报{ 标签:键+ “(” +项目+ “)”, 值:关键 } })) } – 2013-02-23 18:46:42

0

刚上线运行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 
+0

我试过使用jsonParse,但它失败了 – 2013-02-23 11:00:33