2012-03-10 57 views
2

我無法抓取通過AJAX調用返回的響應JSON數據。這是我回到螢火蟲的東西。用jQuery顯示ColdFusion JSON響應

{"COLUMNS":["ID","NAME","REGION","EMAIL"],"DATA":[["1234","John Doe","West","[email protected]"]]} 

這裏是我的腳本:

$.ajax({ 
     url: "action.cfc?method=getEmployees&returnformat=json&queryFormat=column",   type: "POST", 
      success: function(response){ 
         console.log(response);// is the data above 
         console.log(response.DATA.NAME[1]); // this doesn’t work 
         console.log(response.DATA['NAME']);//and this doesn’t work 
    } 
}); 

我得到在Firebug這個錯誤試圖控制檯登錄名稱時「response.DATA未定義」。我錯過了什麼?預先感謝您的幫助!

回答

3

response.DATA是數組的數組,所以你需要索引每個級別。

console.log(response.DATA[0][1]); 

編輯:如果你想使用鍵/值配對,你將需要創建一個CF的struct代替陣列

您還應該設置數據類型:在$就

+0

謝謝你的迴應,這就像一個魅力! – user752746 2012-03-10 06:58:05

+2

如果我要在jQuery中使用結果,我發現從CF web服務返回結構而不是查詢是很有用的。 – 2012-03-11 02:08:32

1

也許就需要從一個字符串解析到一個對象:

success: function(response){ 
    console.log(response);// is the data above 
    response = JSON.parse(response) 
    console.log(response);// is the data above 
} 
+0

謝謝比利,剛剛遇到另一個問題,並解析響應成一個對象解決了它。 – user752746 2012-09-12 21:53:32

+0

我想指出IE8有問題。 – user752746 2012-09-12 23:00:34

+0

他們說IE8是新的IE7,IE7是新的IE6!他們都有很多問題,但似乎IE的最新版本最終變得更符合DOM。 – 2012-09-13 00:56:46

0
「JSON」
 
Looping through the response recieved, using $.each() jquery function, will be able to access the data returned from CF. 
For the above response: 
Example, 
$.each(response,function(mainKey,mainValue){ 
    console.log(mainKey); //displays 'COLUMNS' & 'DATA' 
    console.log(mainValue);// displays ["ID","NAME","REGION","EMAIL"] & ["1234","John Doe","West","[email protected]"] 
    $.each(value,function(innerKey,innerValue){ 
     console.log(innerValue); //displays 'id','value'....,'1234',..and so on 
    }); 
});