2020年11月24日 星期二

[JavaScript] 練習使用 fetch

 index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Code or Nocode</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script>
      function getAnswer() {
        const ul = document.getElementById('answer'); 
        const url = 'http://localhost/test/answer.html'
        fetch(url)
          .then((resp=> resp.json())
          .then(function(data) {
            ul.innerText = "Answer="+data.answer
        })
        setTimeout(getAnswer1000);
      }
    </script>
  </head>
  <body>
    <h1 id="answer">Answer=</h1>
    <script>
      setTimeout(getAnswer1000);
    </script>
  </body>
</html>

 

answer.html

{"answer":"3"}