使用JSON使用jQuery填充UL

时间:2012-10-11 20:26:46

标签: javascript jquery html asp.net-mvc json

这是我的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对象。一旦我发现了这一点,数据开始流下来,并且建议的更改就可以了。

2 个答案:

答案 0 :(得分:13)

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

function populateSavedCounties(select, data) {
    var items = [];
    $.each(data, function (id, option) {
        items.push('<li>' + option.Name + '</li>');
    });  
    select.html(items.join(''));
}

答案 1 :(得分: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);
    };
});