2012-10-14 46 views
0

我想迭代JSON对象,我无法迭代它。如何迭代JSON使用jquery ajax

CS:

[WebMethod] 
public static List<TicVersion> GetTicVersionList() 
{ 
    List<TicVersion> versionList = new List<TicVersion> 
              { 
               new TicVersion 
                { 
                 Date = DateTime.Now, 
                 Version = "2" 
                }, 
               new TicVersion 
                { 
                 Date = DateTime.Now, 
                 Version = "4" 
                }, 
               new TicVersion 
                { 
                 Date = DateTime.Now, 
                 Version = "13" 
                }, 
               new TicVersion 
                { 
                 Date = DateTime.Now, 
                 Version = "28" 
                }, 
              }; 
    return versionList; 
} 


public class TicVersion 
{ 
    public DateTime Date { get; set; } 
    public string Version { get; set; } 
} 

的ScriptManager

<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" 
    runat="server" /> 

JS:

$.ajax({ 
    type: "POST", 
    url: "ManagerTic.aspx/GetTicVersionList", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    async: false, // TODO! 
    success: function (result) { 
     createTicVersionList(result); 
    } 
}); 


function createTicVersionList(result) { 
    var items = []; 
    $.each(result.d, function (key, val) { // here is the problem.... i am not being able to get the values 
     items.push('<li id="' + val.Version + '" class="ui-widget-content">' + val.Date + '</li>'); // i need the actual Date and Version 
    }); 
    $('<ol/>', { 
     'id': 'selectable', 
     'class': 'ui-selectable', 
     html: items.join('') 
    }).appendTo('.baseVersion'); 
} 

EDIT

> if i console.log(result) inside the each, i am getting 
> - Object 
> - - d 
> - - - [0] 
> - - - [1] 
> - - - [2] 
> - - - [3] 
+1

Val.Date使用大写字母,但您的变量使用小写字母声明。如果你写了console.log(val),它是否在每个循环内输出一些东西? –

+0

当你console.log(result)时会发生什么; ?你能告诉我们你回来的是什么吗? –

+0

当我console.log结果,我越来越对象 - > D - >和4项的数组 – user829174

回答

0

result.d在这里没有意义,应该只是result

所以你的情况替换此

$.each(result.d, function (key, val) { 
    // existing 
} 

随着

$.each(result, function (key, val) { 
    // existing 
} 

这将解决您的问题。

+0

请参阅我的编辑上面有关我在console.log – user829174