8

这是我的 JSON 数据

[
    {"CountyId":2,"Name":"Snohomish","StateId":1,"State":null,"Plans":null},    
    {"CountyId":1,"Name":"Whatcom","StateId":1,"State":null,"Plans":null}
]

我正在尝试使用此数据在我的网页上填充 UL。

function loadSavedCounties() {
    $.post("/Plans/GetPlanCounties/",
        { planId: $("#PlanId").val() },
        function (data) {
            populateSavedCounties($("#SavedCounties"), data);
        }
    );
}
function populateSavedCounties(select, data) {
    select.html('');
    var items = [];
    $.each(data, function (id, option) {
        items.push('<li>' + option.Name + '</li>');
    });  
    select.append(items.join(''));
}

我知道我正在成功调用 ,loadSavedQueries()因为我的 UL 正在被调用清除select.html('')。但是没有物品被放回 UL。

更新...

在明显的修复和更改不起作用之后,我在控制器中发现了一个问题,该问题没有引发错误,但基本上返回了空的 JSON 对象。一旦我发现这一点,数据就开始向下流动,建议的更改就成功了。

4

2 回答 2

13

您可以在最后设置 UL 的 html - 无需先将其清除:

function populateSavedCounties(select, data) {
    var items = [];
    $.each(data, function (id, option) {
        items.push('<li>' + option.Name + '</li>');
    });  
    select.html(items.join(''));
}
于 2012-10-11T20:31:10.267 回答
0

这个很简单,我先写代码,然后再回去解释。

脚本

// You obviously know how to use .post
$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
    // out of simplicity, i did not create a seperate function, however you seem to know how to move functions around
    // below of course i simply assign a variable for reuse to the element you want
    var $this = $("#SavedCounties").empty();
    // instead of .each, I went on the premise that your data is returned exactly as stated above,
    // in which case, a simple old school for statement is easiest
    for (x in data) {
        // this is real simple, the first part creates a jQuery object of a List Element
        // the text part adds the text too it (aka, html you were wanting)
        // the last part appends the Li to the END of the UL
        $("<li />").text(data[x].Name).appendTo($this);
    };
});

最终结果没有评论,很短很甜

$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
    var $this = $("#SavedCounties").empty();
    for (x in data) {
        $("<li />").text(data[x].Name).appendTo($this);
    };
});
于 2012-10-11T20:36:41.300 回答