简体   繁体   中英

Fetch request returns nothing

I am trying to perform a Fetch request to an external API, and it should return some JSON data. I have tested the request in my browsers console and it worked fine, however as soon as I add this code to run when I submit a form, it doesn't seem to do anything. No error, it just does nothing.

This is my function:

async function getStats() {
    let username = document.forms["usernameSearch"]["username"].value.toLowerCase();
    let response = await fetch(`https://api.hypixel.net/player?key=${key}&name=${username}`);
    let data = await response.json();
    console.log(data);
}

This is the HTML for the form:

<form name="usernameSearch" onsubmit="getStats()">
    <input type="text" name="username" placeholder="Username..." />
    <input type="submit" value="Go!" />
</form>

No matter what I type in, when I click submit on the form the page just refreshes and the console shows nothing.

You need to prevent the default behavior of onsubmit. You can change the attribute value to

<form name="usernameSearch" onsubmit="onsubmit="event.preventDefault(); getStats()"">

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