【问题标题】:Javascript ""Function not found"Javascript ""未找到函数"
【发布时间】:2022-01-15 10:53:00
【问题描述】:

我有一个非常简单的 HTML 页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test 2 V2</title>
</head>
<body>
    <p>
        <label id="wordCat"></label>
        <input type="text" id="txtCat">
        <input type="button" id="btnCat" value="Load Word" onclick="fetchData(document.getElementById('txtCat').value)">
    </p> 
    <p>
        <label>Your Guess Word is:</label>
        <label id="hiddenWord"></label>
    </p>
    <script src="scripts/app.js"></script>
</body>
</html>

点击按钮时应该调用函数:

async function fetchData(req) {
    console.log(req.value)
    let response = await fetch(req);
    var selectBox, option, prop;

    

    selectBox = document.getElementById("drivers");

    if (response.statusText == "OK") {
        return await response.json();      
    }else{
        throw new Error(response.statusText);
    }
}

问题是当我点击按钮时它显示:GET http://127.0.0.1:5500/{input value in the text box} 404 (Not Found)

谁能帮我解决这个问题?此方法应该加载 json 文件中存在的所有键并打印它们。

words.json

{
    "sports":       ["golf", "hockey", "football"],
    "animals":      ["giraffe", "snake", "lizard", "puma"],
    "video games":  ["pacman", "asteroids", "super mario brothers", "donkey kong"]
}

我需要在 HTML 页面上按字母顺序打印键。

谢谢。

【问题讨论】:

  • 除了语法错误之外,您不应该以这种方式使用内联事件处理程序。
  • 您正在向该端点发出 ajax get 请求,而您的浏览器告诉您该端点不存在。您在服务器上设置了哪些 API 路由(如果有)?听起来你好像错过了它们,需要做一些研究来为你正在使用的服务器技术设置 API 路由

标签: javascript html json


【解决方案1】:

尝试将点击事件监听器附加到脚本页面中的按钮。

document.getElementById('btnCat').addEventListener('click', ()=>{
    const value = document.getElementById('txtCat').value;
    fetchData(value);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多