2010-10-07 63 views
1

當我嘗試從JSON響應中獲取值時,我彈了起來。這裏是我的代碼如何從AJAX響應中檢索JSON變量

代碼:

$.ajax({ 
    url: 'checkvotes.php', 
    dataType: "json", 
    success: function(data) { 
    // want to fetch UP and DOWN variables from JSON here 
    } 
}); 

AJAX從PHP

{"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]} 
+0

你試過了什麼? – Quentin 2010-10-07 12:42:38

+1

alert(data.id);其中說undefined – Rajasekar 2010-10-07 12:45:35

+0

該對象沒有id屬性,它只有一個示例屬性(其長度爲1的數組作爲其值... – Quentin 2010-10-07 12:50:39

回答

5
$.ajax({ 
    url: 'checkvotes.php', 
    dataType: "json", 
    success: function(data) { 
     var up = data.sample[0].up; 
     var down = data.sample[0].down; 
    } 
}); 
0
var up = data['sample'][0]['up'], 
    down = data['sample'][0]['down'] 

剛剛打印的console.log(數據)檢查您的JSON響應

1

嘗試data.sample[0].updata.sample[0].down。如果有疑問,可以使用這個JavaScript來模擬電話:

var data = {"sample":[{"id":"1","message":"my message","up":"200","down":"34"}]}; 

運行在一個調試器和檢查data