2013-03-07 123 views
1

我知道有些人提出同樣的問題並得到解答。我已經看過所有這些,但我仍然無法解決我的問題。我有一個jQuery snipet發送值給處理程序,處理程序處理來自JS的值並將數據作爲JSON數據返回。 JSON數據有兩組記錄(來自數據庫的兩行)需要通過getJSON來捕獲並處理它。 JSON數據看起來就像是

[{"Name":"P1","Description":"pd1",Value":"S1Test1"},{"Name":"P1","Description":"pd1","Value":"L1Test1"}] 

我的JS是

$(document).ready(function() { 
    $.getJSON('ProfileHandler.ashx', { 'ProfileName': 'P1' }, function (data) { 
     alert(data.Name); 
    }); 
}); 

和我的處理程序代碼是

string ProfileName = context.Request["ProfileName"]; 
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService(); 
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = ProfileName }); 
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); 
string serProfileDetails = javaScriptSerializer.Serialize(ProfileDetails); 
context.Response.ContentType = "text/json"; 
context.Response.Write(serProfileDetails); 

什麼是方法錯誤嗎?

回答

7

data是對象的數組

data[0].name 

應該足以獲取第一個名字。

要遍歷整個數組,你可以這樣做:

$.each(data, function(k, v){ 
    alert(v.name); 
}); 

哪裏v是數組中的當前對象。請注意0​​

+0

你給了我比我問的更多,感謝隊友。 – Sandy 2013-03-07 08:43:35

+0

@Sandy Np,很高興幫助 – Johan 2013-03-07 09:09:14

1

您的JSON定義了一個數組,它具有對象作爲條目。因此,而不是

alert(data.Name); 

你想要

alert(data[0].Name); 

(當然,其他指標還有,在你的榜樣,你有01)。

(所引用的JSON也是[失蹤"第一Value前]無效,但我猜這是在問題的拼寫錯誤。)

+0

謝謝你的寶貴意見 – Sandy 2013-03-07 08:35:04