解析后元素消失 JSON

Disappearing element after parsing JSON

我有一个有趣的问题:我写了一个 HTML/JS 项目,通过 XMLHttpRequest 从 Scratch 网站获取信息。目标是让某人输入他们的用户名并使用 JSON.parse 查看他们在 Scratch 上的个人资料中的描述。它似乎可以工作,但描述会短暂出现并消失。我已经扫描了我的代码,但仍然无法将描述保留在那里。我不会 post Stack Overflow 上的代码(太多),但您可以在 https://getthatdesc--micahlt.repl.co/ 查看我的代码和输出。如果有人能提供帮助,我将不胜感激!

您正在提交表单,默认行为是在提交表单时刷新页面

您的代码:

function showInfo() {
// set xhttp as an identifier of XMLHttpRequest
var xhttp = new XMLHttpRequest();
// every time the state of the request changes, evaluate
xhttp.onreadystatechange = function() {
  // These codes mean that the request is finished
  if (this.readyState == 4 && this.status == 200) {
    // Parse the JSON response
    var userParsed = JSON.parse(this.responseText);
    // log the response to the console
    console.log(userParsed);
    // get the description
    var description = userParsed.profile['bio'];
    // log description to the console
    console.log(description);
    // make the output visible to the user
    document.getElementById("info1").innerHTML = description;
  };
};
xhttp.open("GET", "https://cors-anywhere.herokuapp.com/api.scratch.mit.edu/users/" +document.getElementById('usrname').value, false);
xhttp.send();
}
/* fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json)) */

这需要更改为:

function showInfo(e) {
  e.preventDefault();
  // set xhttp as an identifier of XMLHttpRequest
  var xhttp = new XMLHttpRequest();
  // every time the state of the request changes, evaluate
  xhttp.onreadystatechange = function() {
    // These codes mean that the request is finished
    if (this.readyState == 4 && this.status == 200) {
      // Parse the JSON response
      var userParsed = JSON.parse(this.responseText);
      // log the response to the console
      console.log(userParsed);
      // get the description
      var description = userParsed.profile["bio"];
      // log description to the console
      console.log(description);
      // make the output visible to the user
      document.getElementById("info1").innerHTML = description;
    }
  };
  xhttp.open(
    "GET",
    "https://cors-anywhere.herokuapp.com/api.scratch.mit.edu/users/" +
      document.getElementById("usrname").value,
    false
  );
  xhttp.send();
}
/* fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json)) */