8

これは私のJSONデータです

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

Web ページの 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 に答える