【问题标题】:JSON data not printing but prints on click (Uncaught TypeError: Cannot read property '1' of null)JSON 数据未打印,但在单击时打印(未捕获的 TypeError:无法读取 null 的属性“1”)
【发布时间】:2021-01-11 21:31:42
【问题描述】:

我正在尝试在 HTML 段落中打印我的数据字符串之一,以测试数据是否正常工作。但是,当我尝试 getElementById 时,我得到了上面的错误。虽然当我使用按钮调用该函数时,我在打印数据时没有问题。我认为这与读取数据的顺序有关,但我不太确定。我使用的代码如下:

<html>
  <head>
    <title>Untitled</title>
  </head>   
  <body>
     
      <p id="demo">  </p>
      
      <script type="text/javascript">
          //Stores data
          var Data = null;
          fetch('fetch.php')
          .then(data => data.json())
          .then(data => {
              //Set data
              Data = data;
              console.log(Data);
          });
          
          document.getElementById("demo").innerHTML = Data[1].name;
         function myFunction() {document.getElementById("demo").innerHTML = Data[1].name;}
         
          
</script>
      <button onclick="myFunction()">Click me</button>
      
  </body>
</html>

【问题讨论】:

标签: javascript php html arrays json


【解决方案1】:

问题是fetch 异步执行其任务,而您试图在其值可用之前访问Data

请尝试以下代码。

我建议您阅读有关 JS Promises 和异步代码执行的更多信息。但是,如果您有任何疑问,请告诉我。

<html>
<head>
    <title>Untitled</title>
</head>
<body>

<p id='demo'>  </p>

<script type="text/javascript">
    let Data = null;
    let myFunction = function () {
        console.log('DATA IS NOT READY YET.');
    };
    
    fetch('fetch.php')
        .then(data => data.json())
        .then(data => {
            myFunction = function () {
                document.getElementById('demo').innerHTML = data[1].name;
            };
        });
</script>

<button onclick="myFunction()">Click me</button>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2022-11-24
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多