Javascript XMLHttpRequest替换元素赢得';不能使用本地存储

Javascript XMLHttpRequest替换元素赢得';不能使用本地存储,javascript,html,ajax,replace,xmlhttprequest,Javascript,Html,Ajax,Replace,Xmlhttprequest,我尝试在javascript代码中使用localStorage实现cookie日志记录,以替换特定元素。它使用XMLHttprequest方法,我不知道为什么它不能与localStorage一起工作。请开导我 localStorage.setItem("replace1", this.JSON.parse(responseText)); function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatech

我尝试在javascript代码中使用localStorage实现cookie日志记录,以替换特定元素。它使用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)请求终止时显示数据

否则您将无法定义,因为该键下的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();
}

我相信repsonseText是一个对象,因此使用
JSON.parse(responseText)
然后从该对象检索属性出于某种原因,它仍然输出“undefined”(未定义)在哪一行代码中得到未定义?我用更改的代码更新了帖子,元素只输出“undefined”(未定义),而根本不显示元素。在该站点上,我认为问题在于您应该将
document.getElementById(“replace1”).innerHTML=localStorage.getItem(“replace1”)
localStorage.setItem(“replace1”,this.JSON.parse(responseText))之后
由于异步行为,您试图在数据来自XHR请求之前显示一些内容,但是JSON.stringify似乎也不起作用,因为它在控制台中为它输出了一个错误。未捕获引用错误:在XMLHttpRequest.xhttp.onreadystatechange中未定义responseText。再次检查,应该是
这个。responseText
太好了,哈。但由于某种原因,当我刷新页面时,元素返回到其默认状态。只有当我点击它时,元素才会变成url。odd@NateVang奇怪的是,本地存储应该保持这种状态。是的,这很奇怪,我的意思是你把一切都搞定了。在这里,您可以看到,当您单击yoinkexecutor元素时,它将更改为url元素,但随后刷新页面,它将返回到默认状态。哈曼密码有时会让人头疼。