我尝试将 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/