【问题标题】:Use data from Json to go to page使用来自 Json 的数据转到页面
【发布时间】:2021-05-13 15:19:55
【问题描述】:

我正在尝试使用 json 制作登录页面。我正在尝试拥有它,因此当有人单击它时,它会转到 json 文件中的页面。到目前为止,我有这个:

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200)
    {
        var Link = JSON.parse(this.responseText);
        document.getElementById("Link1").innerHTML = Link.title;
    }
};

xmlhttp.open("GET", "link.json", true);
xmlhttp.send();
      
function click1(){ 
    window.location.href = Link.link;
}

当我点击它时,它会给我(从控制台):

(index):22 Uncaught ReferenceError: Link is not defined at click1 ((index):22) at HTMLAnchorElement.onclick ((index):8)

【问题讨论】:

  • Linkxmlhttp.onreadystatechange 的本地,因此您无法从 click1 引用它。为什么不把整个 XMLHttpRequest 例程放在 click 函数体中呢?

标签: javascript html json


【解决方案1】:

假设您的 JSON 内容具有属性 titlelink,并且您的 click1 处理程序已正确注册,您应该能够将您拥有的内容组合成如下内容:

function click1() { 
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var Link = JSON.parse(this.responseText);
      document.getElementById("Link1").innerHTML = Link.title;
      window.location.href = Link.link;
    }
  };
  xmlhttp.open("GET", "link.json", true);
  xmlhttp.send();
}

请注意,在window.location.href = Link.link; 之前设置元素的innerHTML 有点毫无意义,因为更新window.location 会导致加载新页面。

【讨论】:

  • 那行得通。我有一个等待命令,以便链接在刷新前几秒钟可见
猜你喜欢
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多