簡體   English   中英

無法使用jQuery填充選擇框

[英]Cannot populate a select box with jquery

我有一個由jQuery填充的選擇框。 這些選項是通過REST調用從服務器獲取的,然后用於填充選擇框。

該應用程序也應該脫機工作,但是當脫機時,這些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));
    }
  }
});

我在.fail()使用console.log ,可以確認數據實際上已經存儲了所有位置對象,但是為什么我的選擇框仍然顯示為空。

問題是因為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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM