【发布时间】:2020-01-16 06:49:02
【问题描述】:
我尝试在 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();
}
【问题讨论】:
-
repsonseText 是一个我相信的对象,因此使用
JSON.parse(responseText);然后从该对象中检索属性 -
由于某种原因它仍然输出“未定义”
-
在哪一行代码中未定义?
-
我用更改的代码更新了帖子,元素只输出“未定义”,根本不显示元素。 i.imgur.com/Wn4JNCI.png现场natevanghacks.com/scriptexecutors2.php
-
我认为问题在于你应该把
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");放在localStorage.setItem("replace1", this.JSON.parse(responseText));之后,因为异步行为,你试图在数据来自XHR请求之前显示一些东西
标签: javascript html ajax replace xmlhttprequest