所以,我试着制作一个天气应用程序,它能给出输入的城市温度,它总是在捕捉中运行代码。当试图调试它时,响应的输出被打印出来,而不是数据。我是一个初学者,所以请忽略我的错误和不正确的代码规则,希望你能帮助我解决这个问题:)!
const submit = document.getElementById("btnsubmit");
const cityname = document.getElementById("cityname");
const city_output = document.getElementById("cityoutput");
const temp_status = document.getElementById('temp_status');
const temp = document.getElementById('temp');
const getInfo = async(event) => {
event.preventDefault();
const cityval = cityname.value;
if (cityval === '') {
city_output.innerText = `please write a value`;
} else {
try {
let url = `api.openweathermap.org/data/2.5/weather?q=${cityval}&units=metric&appid=(myapiid)`;
const response = await fetch(url);
// console.log(response);
const data = await response.json();
// console.log(data);
const arrData = [data];
// console.log(arrData);
temp.innerText = arrData[0].main.temp;
temp_status.innerText = arrData[0].weather[0].main;
} catch {
city_output.innerText = `please write city name properly`;
}
}
};
submit.addEventListener('click', getInfo);
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<title>Hello, world!</title>
</head>
<body>
<div class="container" id="main">
<form>
<div class="mb-3">
<label " class="form-label">Eneter City Name</label>
<input type="text" class="form-control" id="cityname" aria-describedby="emailHelp">
</div>
<button type="submit" class="btn btn-primary" id="btnsubmit" >Submit</button>
</form>
<div id="cityoutput">
cityname
</div>
<div id="temp_status">cloudy</div>
<div id="temp">0 ° C</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
样本数据:
{
"coord": {
"lon": 75.8333,
"lat": 22.7179
},
"weather": [{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}],
"base": "stations",
"main": {
"temp": 30.1,
"feels_like": 33.44,
"temp_min": 30.1,
"temp_max": 30.1,
"pressure": 1000,
"humidity": 62
},
"visibility": 6000,
"wind": {
"speed": 5.14,
"deg": 140
},
"clouds": {
"all": 20
},
"dt": 1626090800,
"sys": {
"type": 1,
"id": 9067,
"country": "IN",
"sunrise": 1626049154,
"sunset": 1626097494
},
"timezone": 19800,
"id": 1269743,
"name": "Indore",
"cod": 200
} {
"mode": "full",
"isActive": false
}
1条答案
按热度按时间xmakbtuz1#
对我来说,它应该能正常工作。我在示例数据中发现的唯一一件事是在最后第三行缺少一个逗号
这是plnkr的链接
https://plnkr.co/edit/tkmpa6a17opxewzx?open=lib%2fscript.js&preview
非常感谢。
巴拉特