XMLHttpRequest和Fetch不起作用



所以我正在进行我的第一个项目,该项目使用JavaScript和HTML,这是一个基本的天气网页。用户输入他们的位置并显示当前天气。HTML工作得很顺利,但JavaScript一直在填充。奇怪的是控制台中没有错误,所以它应该可以正常工作。

这是HTML的一部分:

<section id="weather">
<div id="nav">
<div id="locate">
<div id="container">
<form id="location-form">
<label for="location">Location (eg. London,uk):</label>
<input type="text" id="location" name="location" required>
<button type="submit" form="location-form" formnovalidate>Let's Go!</button>
</form>
</div>
</div>
<div id="weather-output">
<!-- Output of API goes here -->

</div>
</div>
</section>

这是我的JavaScript。我使用脚本标记嵌入了它,因为它没有检测到按钮按下。

<script type="text/JavaScript">
function fetchAPIData() {
const locationInput = document.getElementById("location");
const locationValue = locationInput.value;
const url = `http://api.openweathermap.org/data/2.5/weather?q=${locationValue}&APPID=API_URL`;
// do the URL Request
async function xmlrequest() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("weather-output").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
xmlrequest(); 
}
//listens for button on html side and runs fetchAPIData()
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("button[type=submit]").addEventListener("click", fetchAPIData);

}
);
</script>

我在XMLHttpRequest(如上所示(和Fetch中都尝试过。两者都不起作用,它们既不起作用也不显示错误。我正在使用OpenWeatherMap,我有一个API密钥,它作为一个普通的url工作,但当它是脚本时,它就不会了。任何帮助都将是惊人的!

mrt

编辑:Firebase分析正在运行,其状态代码为"200"。API没有任何状态代码或错误消息。更新了代码,现在有一个错误"400",所以它仍然不起作用,但我现在可以解决它。感谢大家的帮助!

解决方案1

问题是你把按钮的类型写成了";提交":

<button type="submit" form="location-form" formnovalidate>Let's Go!</button>

尝试类型=";按钮":

<button type="button" form="location-form" formnovalidate>Let's Go!</button>

并修改js:

document.querySelector("button[type=button]").addEventListener("click", fetchAPIData);

解决方案2

使用e.preventDefault((函数:

function fetchAPIData(e) {
e.preventDefault();
const locationInput = document.getElementById("location");
const locationValue = locationInput.value;
.....

除了James写的fetchasync/await应该仍然是前进的方向。

一个基本的(人为的(例子:

// Make this function async
async function fetchAPIData() {
// Get the value from your input
const { value } = locationInput;
const endpoint = `http://api.openweathermap.org/data/2.5/weather?q=${value}&APPID=API_URL`;
// Await the response
const response = await fetch(endpoint);
// If it's ok parse the data and update the DOM
// otherwise throw an error
if (response.ok) {
const data = await response.json();
output.innerHTML = data;
} else {
throw new Error('Bad response');
}
}

最新更新