2017-05-25 147 views
1

我有一個選擇框,我被jQuery填充。這些選項通過REST調用從服務器獲取,然後用於填充選擇框。無法使用jquery填充選擇框

該應用程序也應該脫機工作,但脫機時,這些REST調用失敗。所以我所做的是當REST調用真正通過時,我將這些值存儲在localStorage內,當脫機和REST調用失敗時,我只是獲取localStorage中存儲的值並嘗試填充選擇框。

但是,選擇框仍顯示爲空。我已經在控制檯中打印了存儲的值,並且顯示這些值實際上已成功存儲和檢索。我不知道爲什麼我的選擇框仍然顯示爲空。

$.getJSON("/openmrs/ws/rest/v1/location", function(result) { 
    var locations = $("#identifierLocations"); 

    localStorage.setItem("locations", result.results); 

    $.each(result.results, function() { 
    locations.append($("<option />").val(this.uuid).text(this.display)); 
    }); 
}).fail(function(jqXHR, textStatus, errorThrown) { 
    var data = localStorage.getItem("locations"); 

    if (data) { 
    var locations = $("#identifierLocations"); 

    for (var i = 0; i < data.length; i++) { 
     locations.append($("<option />").val(data[i].uuid).text(data[i].display)); 
    } 
    } 
}); 

我用console.log.fail(),我可以證實的數據實際上擁有所有存儲位置的對象,但爲什麼我的選擇框仍顯示爲空。

+1

你可以發佈你的HTML嗎? – Drala

+2

'localStorage'只能存放字符串。你需要將它們存儲之前連載的'result.results',然後檢索他們的時候 –

+0

待辦事項localStorage.setItem(「位置」,JSON.stringify(result.results)) 和JSON.parse(數據)使用它deserialise他們 –

回答

2

的問題是,因爲localStorage只能容納字符串。在存儲它們之前,您需要序列化result.results,然後在取回它們時進行反序列化。試試這個:

$.getJSON("/openmrs/ws/rest/v1/location", function(result) { 
    localStorage.setItem("locations", JSON.stringify(result.results)); 
    populateLocations(result.results); 
}).fail(function(jqXHR, textStatus, errorThrown) { 
    var data = localStorage.getItem("locations"); 
    if (data) { 
    populateLocations(JSON.parse(data)); 
    } 
}); 

function populateLocations(locations) { 
    var html = locations.map(function(o) { 
    return '<option value="' + o.uuid + '">' + o.display + '</option>'; 
    }).join(''); 
    $("#identifierLocations").html(html); 
} 
+0

這工作。謝謝。 – ivange94