javascript - XMLHttpRequest 替换元素不适用于 LocalStorage

标签 javascript html ajax replace xmlhttprequest

我尝试将 cookie 日志记录与 localStorage 实现到 javascript 代码中以替换特定元素。它使用 XMLHttprequest 方法,我不知道为什么它不能与 localStorage 一起使用。请赐教。

localStorage.setItem("replace1", this.JSON.parse(responseText));

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       document.getElementById("replace1").innerHTML = localStorage.getItem("replace1"); 
    }
  };
  xhttp.open("GET", "yoinkexecutor2.php", true);
  xhttp.send();
}

最佳答案

您只能在异步操作 (GET) 请求终止时显示数据。

否则你会得到 undefined 因为在该键下的 localStorage 中没有任何东西存在

此外,您只能将字符串存储在本地存储中,这意味着一旦您想要使用 getItem 检索数据,就需要解析该对象字符串

 function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      localStorage.setItem("replace1", JSON.stringify(this.responseText))
      document.getElementById("replace1").innerHTML = JSON.parse(localStorage.getItem("replace1"))
    }
  };
  xhttp.open("GET", "yoinkexecutor2.php", true);
  xhttp.send();
}

关于javascript - XMLHttpRequest 替换元素不适用于 LocalStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939791/

相关文章:

javascript - 为 xmlhttprequest 对象提供属性

javascript - 创建 AJAX 调用时 - 我需要请求什么样的数据?

php - IE 打开两个弹出窗口而不是一个

javascript - NodeJs 在函数内初始化数组

html - Bootstrap 中等高和等宽的盒子?

javascript - 如何在数据表中过滤 AJAX 调用的输出?

html - 正确的 HTML5 (+ schema.org) 标记文章的发布日期和位置

android - 溢出 :hiden with border-radius on mobile browser

php - jQuery AJAX 发布不工作

php - 用于更新 WooCommerce 管理产品列表中库存数量的自定义输入字段