【问题标题】:How do I save xml file to local storage and update values when user is offline?用户离线时如何将 xml 文件保存到本地存储并更新值?
【发布时间】:2019-06-27 14:36:51
【问题描述】:

我正在尝试编写货币转换器。我正在从存储货币和汇率的 url 下载 xml 文件。我想将货币保存到本地存储中,这样当用户离线时,他仍然可以进行转换。我在控制台中打印 xml 文件只是为了检查我是否正在获取 xml 文件。所以我的问题是,我如何将货币和汇率存储到本地存储,以及当用户再次在线时如何更新值? 脚本:

function display(e ) {
    if ((e.target !== e.currentTarget) && e.target.id !== "clear" && e.target.id !== "kati") {
        var clickedItem = e.target.id;
        document.getElementById("display").value =  document.getElementById("display").value + clickedItem;
    }
    else  if (e.target.id = "clear" && e.target.id !== "kati") {
        document.getElementById("display").value = null;
    } else if (e.target.id = "kati") {
        var ourRequest = new XMLHttpRequest();
        ourRequest.open('GET', 'https://devweb2018.cis.strath.ac.uk/~aes02112/ecbxml.php');
        ourRequest.onreadystatechange = function () {
            var data = ourRequest.responseText;
            console.log(data);
        };
        ourRequest.send();
    }
    e.stopPropagation();
}

xml 文件的 url 显示在代码中。

【问题讨论】:

  • 据我所知,您只是在问如何使用localStorage;您发布的代码并不真正相关。你都尝试了些什么?并不比localStorage.setItem('currencies', some_string_possibly_json);难多少,思路是加载完数据就存储起来,如果加载失败,就从localStorage读取吧。

标签: javascript html xml-parsing


【解决方案1】:

是的,正如 Chris 已经说过的,您可以使用默认的 localStorage:

localStorage.setItem("hello","world");
localStorage.getItem("hello"); //world

例如,收到回复后

ourRequest.onreadystatechange = function () {
 if (ourRequest.readyState === 4) {
  if (xhr.status == 200){
   if (ourRequest.status == 200){
     var data = ourRequest.responseXML;
     var someTag = data.getElementsByTagName("someTag");
     //something like this
     localStorage.setItem("someTagValue",someTag[0].childNodes[0].nodeValue);
   }
  }    
};

【讨论】:

猜你喜欢
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 2021-09-29
相关资源
最近更新 更多