代码之家  ›  专栏  ›  技术社区  ›  S Andrew

从javscript调用api时未获得任何响应时出错

  •  0
  • S Andrew  · 技术社区  · 6 年前

    apitest.php文件

    <!DOCTYPE html>
    <html>
    
        <head>
            <title>WEBPAGE</title>
            <link href="main.css" rel="stylesheet" type="text/css" href="" />
            <script type="text/javascript">
    
                function test(){
                    const userAction = async () => {
                    const response = await fetch('<some_api_url>');
                    const myJson = await response.json(); 
                    document.getElementById("demo").innerHTML = myJson
                    }
                }
            </script>
        </head>
    
        <body>
                <button onclick="test()">Click</button>
                <p id="demo"></p>
    
        </body>
    
    </html>
    

    我正在尝试演示调用GET api,其响应是非常基本的json数据:

    {"Status":"OK"}

    1 回复  |  直到 6 年前
        1
  •  1
  •   Robin Zigmond    6 年前

    你的 test userAction 发出API请求。但是这个函数永远不会被调用,所以请求永远不会被发送。

    只需添加以下行:

    userAction()
    

    功能。