简体   繁体   English

获取请求不返回任何内容

[英]Fetch request returns nothing

I am trying to perform a Fetch request to an external API, and it should return some JSON data.我正在尝试对外部 API 执行Fetch请求,它应该返回一些 JSON 数据。 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:这是我的 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:这是表格的 HTML:

<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.您需要防止 onsubmit 的默认行为。 You can change the attribute value to您可以将属性值更改为

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

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

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