脚本运行后,体内的HTML代码就会执行

时间:2018-09-03 12:46:39

标签: javascript html

我是Java语言的新手,我正在尝试发出http请求以获取一些数据并以html显示结果。我正在获取结果并更新html代码,但是正文中的html代码会重新加载并显示默认值。我的代码是,

<head>
  <script>
    function httpGetAsync() {

      var results = new Array(3);
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.send();
      xhr.addEventListener("readystatechange", processRequest, false);
      xhr.onreadystatechange = processRequest;

      function processRequest() {

        if (xhr.readyState == 4 && xhr.status == 200) {

          // populate here results array

          // i change the value with the following line
          document.getElementById("title_1").innerText = "fetched_value";

        }
      }
    }
  </script>
</head>

<body>

  <div class="search_btn">

    <form id="search_form" method="get" onSubmit="return httpGetAsync()">

      <input type="text" class="search" placeholder="Search" id="search">
      <input type="submit" value="search" class="search_button">

    </form>

  </div>

  <div id="one">

    <p id="title_1">default</p>

  </div>
</body>

“ title_1”将其文本更改为“ fetched_value”,然后重新加载并再次变为“ default”。我在做什么错了?

2 个答案:

答案 0 :(得分:2)

这是因为您的onSubmit没有收到false。只需将return false添加到httpGetAsync结尾

function httpGetAsync() {
  var results = new Array(3);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.send();
  xhr.addEventListener(
      "readystatechange",
       function processRequest() {
          if (xhr.readyState == 4 && xhr.status == 200) {
              document.getElementById("title_1").innerText = "fetched_value";
          }
       },
       false);
  xhr.onreadystatechange = processRequest;

  return false;
}

答案 1 :(得分:0)

您需要阻止对提交的默认操作,即使用form元素上的“ action”属性重新加载页面(如果不存在,则重新加载当前页面)。

function httpGetAsync(event) {
  event.preventDefault();
  ...
}