首页 > 解决方案 > 无法使用 Fetch API 显示来自承诺的值

问题描述

我对Javascript世界很陌生,并试图通过REST API使用 using来运行一个简单的程序Fetch API

我的HTML文件有一个按钮,点击它会点击 aREST API并在页面上显示值。

问题是这些值没有显示在页面上。请指导。

主页.html

<html>
        <head>
            <title>Fetch API Demo</title>
        </head>
        <body>
            <h1>Config files</h1>
            <button onclick="showUser();">Show user</button>
        </body>
        <script>
            function showUser() {
                fetch('https://jsonplaceholder.typicode.com/users/1')
                    .then(function (response) {
                        console.log('status: ${response.status}');
                        console.dir(response.body);
                        return response.json(); // the important line
                    })
                    .then(function (myJson) {
                        document.write('User: ${myJson.name} <br/> Email: ${myJson.email} <br/> Website: ${myJson.website}');
                        return myJson;
                    })
                    .then(console.log);
            }
        </script>
    </html>

网页(截图):

在此处输入图像描述

标签: javascriptajaxpromisefetchfetch-api

解决方案


您给出了无效的模板字符串,模板字符串以 `(反引号)开头和结尾。

<html>

<head>
  <title>Fetch API Demo</title>
</head>

<body>
  <h1>Config files</h1>
  <button onclick="showUser();">Show user</button>
</body>
<script>
  function showUser() {
    fetch('https://jsonplaceholder.typicode.com/users/1')
      .then(function(response) {
        console.log('status: ${response.status}');
        console.dir(response.body);
        return response.json(); // the important line
      })
      .then(function(myJson) {
        document.write(`User: ${myJson.name} <br/> Email: ${myJson.email} <br/> Website: ${myJson.website}`);
        return myJson;
      })
      .then(console.log)
      .catch(err => {});
  }
</script>

</html>


推荐阅读