You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API调用在VS Code运行器正常但HTML页面失效问题求助

解决表单提交时fetch请求被中断的问题

问题核心是表单的默认提交行为导致页面刷新,直接中断了fetch请求。当你点击提交按钮后,getWeather()函数返回true,浏览器会执行表单默认的GET提交流程,页面刷新,正在进行的fetch请求被终止,所以看起来卡在fetch调用处;而在VS Code运行器中直接调用函数,没有触发表单的默认提交流程,因此请求能正常完成。

方案一:修改函数返回值阻止默认提交

修改JavaScript代码的else分支,将return true改为return false,阻止浏览器执行表单的默认提交行为:

function getWeather() {
    let city = document.forms["weather-form"]["city"].value
    // let city = "New York";
    if (city == "") {
        alert("Name must be filled out");
        return false;
    }
    else {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`)
            .then(response => response.json())
            .then(data => {
                console.log(data);
            })
            .catch(err => console.error("请求出错:", err)) // 添加错误捕获,便于排查问题
        return false; // 阻止表单默认提交
    }
}

方案二:使用事件对象阻止默认行为

先修改HTML的表单onsubmit属性,传递事件对象:

<form name="weather-form" onsubmit="getWeather(event)" method="get">
    <input class="placeholder" type="text" name="city" placeholder="Search for a city">
    <input class="button" type="submit" value="Weatherize">
</form>

然后在JavaScript函数中调用preventDefault()阻止默认提交:

function getWeather(event) {
    event.preventDefault(); // 阻止表单默认提交行为
    let city = document.forms["weather-form"]["city"].value
    // let city = "New York";
    if (city == "") {
        alert("Name must be filled out");
        return;
    }
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
        })
        .catch(err => console.error("请求出错:", err)) // 添加错误捕获
}

额外建议

  • 始终添加catch()方法捕获fetch请求中的错误(比如网络问题、API返回错误状态码等),避免出现无反馈的异常情况。
  • 可以对API返回的response进行状态检查,比如判断response.ok是否为true,针对性处理API返回的错误信息。

内容的提问来源于stack exchange,提问作者Arthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:21:57