반응형
리액트로 만들려고 했는데,
uncaught (in promise) syntaxerror: unexpected token < in json at position 0
에러의 비밀을 풀지 못하고 접었다.
아쉬워서 DOM으로나마 만들었다. 후
도시 이름은 API에 등록된 이름만 가능하다. NewYork이라 치면 안나오고 New York이라 쳐야 한다.
CSS는 귀찮아서 안했다.
https://github.com/ryu9663/weatherAlarm.git
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="globals.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<input id = 'city' type = 'textbox'/>
<input type = 'submit' id = changeCity value = '클릭'/>
</form>
<div class = "de">
<h5>기본값</h5>
</div>
<script src='weather.js'></script>
</body>
</html>
const weatherLine = document.createElement('h4')
const temperatureLine = document.createElement('h4')
const cityLine = document.createElement('h4')
const de = document.querySelector('.de')
document.body.append(weatherLine)
document.body.append(temperatureLine)
document.body.append(cityLine)
let city = document.querySelector('#city')
let button = document.querySelector('#changeCity')
let count = 0
let cityName = 'Jecheon'
button.addEventListener('click',func)
function func(event){
event.preventDefault()
count++
if(count === 0){ cityName = 'Jecheon'}
else{cityName = city.value}
const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${API_KEY}`
fetch(url)
.then(response => response.json())
.then(data => {
weatherLine.textContent = data.weather[0].main
temperatureLine.textContent = `${(data.main.temp-273).toFixed(2)}도`
cityLine.textContent = data.name
})
}
// const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=479b71bd8170440dd418a65c5c00da87`
fetch(`https://api.openweathermap.org/data/2.5/weather?q=Jecheon&appid=${API_KEY}`)
.then(response => response.json())
.then(data => {
weatherLine.textContent = data.weather[0].main
temperatureLine.textContent = `${(data.main.temp-273).toFixed(2)}도`
cityLine.textContent = data.name
})
de.append(weatherLine)
de.append(temperatureLine)
de.append(cityLine)
반응형
'개발 > Javascript' 카테고리의 다른 글
JS, Object.assign (0) | 2021.09.20 |
---|---|
JSON(JavaScript Object Notation) (0) | 2021.09.11 |
JS : 꼬리재귀는 일반재귀함수가 가진 메모리,성능 문제를 해결한다. (0) | 2021.08.30 |
JS : Super와 extends를 이용한 클래스 상속 (0) | 2021.08.23 |
JS: call, apply, bind (0) | 2021.08.22 |