首页 > 解决方案 > 用户离线时如何将 xml 文件保存到本地存储并更新值?

问题描述

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

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 显示在代码中。

标签: javascripthtmlxml-parsing

解决方案


是的,正如 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);
   }
  }    
};

推荐阅读