2017-05-25 148 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