简体   繁体   中英

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:

<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. When I run fetch_data() outside of the.click() function, it runs perfectly.

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.

Try calling your function with the URL you want instead.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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