简体   繁体   English

Javascript fetch() function 在点击时不起作用

[英]Javascript fetch() function doesn't work on click

I have a simple code that asks the program to fetch some data using fetch() when I click the button:我有一个简单的代码,当我单击按钮时,它要求程序使用 fetch() 获取一些数据:

<button id="hello-btn">Say Hello!</button>
<script>
    var route = "/a-url";
    let fetch_data = (route) => {
        fetch(route)
            .then(res => res.text())
            .then(data => $("#resp").text(data))
    }
    
    $("#hello-btn").click((route) => {
        fetch_data(route);
    });
</script>

When I click the button, fetch_data() would not run.当我单击按钮时, fetch_data() 不会运行。 When I run fetch_data() outside of the.click() function, it runs perfectly.当我在.click() function 之外运行 fetch_data() 时,它运行良好。

Any explanation as to why?任何解释为什么? Thank you!谢谢!

The problem is that on your #hello-btn click function you are defining route as the click event object and passing that as the route variable to be used in your function.问题是在您的#hello-btn 点击 function 您将route定义为点击事件 object 并将其作为路由变量传递给您的 ZC1C425268E68385D1AB5074C17A94F1.

Try calling your function with the URL you want instead.尝试使用您想要的 URL 来调用您的 function。

 let fetch_data = (route) => { fetch(route).then(res => res.text()).then(data => $("#resp").text(data)) } $("#hello-btn").click((e) => { fetch_data("/a-url"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="hello-btn">Say Hello!</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM