[항해99] 웹개발 종합반 2주차 (내용정리)
오늘은 javascript, jquery, ajax 를 이용하는 방법들을 배웠다
# JQuery, Ajax
# 자바스크립트를 이용한 홀 짝 찾기
간단하다 그냥 %해서 0이면 짝수 1이면 홀수 라고 표시해줬다
let even = 4;
console.log(even % 2); // 2로 나눈 나머지가 0입니다.
let odd = 5;
console.log(odd % 2); // 2로 나눈 나머지가 1입니다.
# JQuery
JQuery란 html의 요소들을 조작하는 편리한 자바스트립트 라이브러리
https://www.w3schools.com/jquery/jquery_get_started.asp
jQuery Get Started
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
JQueryCDN에서 미리 소스를 맨위에 붙여줘야 사용가능하다
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
css때는 class로 주로 지칭했다면
jquery에서는 id로 지칭한다
id값을 지정할때는 $('#id값') <- () 소괄호
변수를 지정할때는 ${변수명} <- {} 중괄호
document.getElementById("element").style.display = "none";
$('#element').hide();
# Input 박스에 값 넣기
$('#id명').val('입력을 하고 싶다')
그러면 input박스에 입력을 하고 싶다 라는 문구가 들어간다
# Input 박스의 값 가져오기
$('#id명').val()
그러면 input박스에 적힌 값을 가져온다
# 해당 객체 숨기기
$('#id명').hide()
# 해당 객체 보이게 하기
$('#id명').show()
# 똑같은 객체 붙여넣기
let temp_html = `여기안에 복사할 html넣기`
참고로 작은따옴표 ' ' 가 아닌 백틱 ` ` 이다
ex) let temp_html = `<li>${변수명}</li>` 또는 `<div>$('id명')</div>`
$('#id명').append(temp_html) <- 해당 div에 복사내용 붙여넣기
# 객체 내용 다 지우기
$('#id명').empty()
# 문자열에 있는지 확인하기
temp.includes('확인할 값')
# 퀴즈
- 1번 답안
function q1() {
// 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
// 2. 만약 입력값이 빈칸이면 if(입력값=='')
// 3. alert('입력하세요!') 띄우기
// 4. alert(입력값) 띄우기
let temp = $('#input-q1').val()
if(temp == ''){
alert('입력하세요!')
}else{
alert(temp)
}
}
- 2번 답안
function q2() {
// 1. input-q2 값을 가져온다.
// 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
// 3. info@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
// 4. alert(도메인 값);으로 띄우기
// 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
let temp = $('#input-q2').val()
if(temp.includes('@')){
let list = temp.split('@')
let list2 = list[1].split('.')
alert(list2[0])
}else{
alert('이메일이 아닙니다')
}
}
- 3번 답안
function q3() {
// 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
// 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
// 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
let txt = $('#input-q3').val()
let temp_html = `<li>${txt}</li>`
$('#names-q3').append(temp_html)
}
function q3_remove() {
// 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
$('#names-q3').empty()
}
# JsonView
api를 가져왔을때 json 값들을 예쁘게 나오게 해주는것이다
(크롬 다운로드해주면 된다)
https://chrome.google.com/webstore/detail/jsonview/gmegofmjomhknnokphhckolhcffdaihd/related?hl=ko
JSONView
브라우저에서 JSON 문서를 보세요.
chrome.google.com
# JSON
# AJAX 처리
openAPI를 이용해서 데이터를 가져와 이용하기 위해
ajax 처리 하는것을 배웠다
# AJAX 기본 골격
$.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
console.log(response)
}
})
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let mise_list = response["RealtimeCityAir"]["row"];
for (let i = 0; i < mise_list.length; i++) {
let mise = mise_list[i];
let gu_name = mise["MSRSTE_NM"];
let gu_mise = mise["IDEX_MVL"];
console.log(gu_name, gu_mise);
}
}
});
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function(response){
let mise_list = response["RealtimeCityAir"]["row"]; // 꺼내는 부분!
console.log(mise_list);
}
})
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let mise_list = response["RealtimeCityAir"]["row"];
for (let i = 0; i < mise_list.length; i++) {
let mise = mise_list[i];
console.log(mise);
}
},
});
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let mise_list = response["RealtimeCityAir"]["row"];
for (let i = 0; i < mise_list.length; i++) {
let mise = mise_list[i];
let gu_name = mise["MSRSTE_NM"];
let gu_mise = mise["IDEX_MVL"];
console.log(gu_name, gu_mise);
}
}
});
아래 예시들은 위의 내용을 종합해서 동일하게 진행된다
1) get방식으로 읽어온다고 설정을하고
2) url을 openAPI 주소로 작성한다
3) 키값 벨류값 인 RealtimeCityAir와 row로 rows 라는곳에 담아 준다
4) rows 값만큼 돌려서 row안에있는 값을 각각 변수에 담아주면 된다
5) 그리고 처음했던 JQuery방식을 이용해서 값을 나타내주면 된다
# 서울시 미세먼지 데이터 크롤링 해보기
<script>
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let rows = response['RealtimeCityAir']['row']
for(let i = 0; i < rows.length; i++){
let gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = ''
if(gu_mise > 40){
temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
}else{
temp_html = `<li>${gu_name} : ${gu_mise}</li>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
# 서울시 따릉이 데이터 크롤링 해보기
<script>
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let rows = response['getStationList']['row']
for(let i = 0; i < rows.length; i++) {
let name = rows[i]['stationName']
let rack = rows[i]['rackTotCnt']
let bike = rows[i]['parkingBikeTotCnt']
let temp_html = ``
if(bike < 5){
temp_html = `<tr class="urgent">
<td>${name}</td>
<td>${rack}</td>
<td>${bike}</td>
</tr>`
}else{
temp_html = `<tr>
<td>${name}</td>
<td>${rack}</td>
<td>${bike}</td>
</tr>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
# 르탄이 API 이용해보기
이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rtan",
data: {},
success: function (response) {
let url = response['url']
let msg = response['msg']
$('#img-rtan').attr('src',url)
$('#text-rtan').text(msg)
}
})
}
</script>
<div class="question-box">
<h2>3. 르탄이 API를 이용하기!</h2>
<p>아래를 르탄이 사진으로 바꿔주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">르탄이 나와</button>
<div>
<img id="img-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
<h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
</div>
</div>
# 기존 방명록에 서울시 온도 나타내기
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
data: {},
success: function (response) {
let temp = response['temp']
$('#temp').text(temp)
}
})
});
</script>
# 느낀점
javascript, jquery, ajax 에대한 이해와 구분을 할 수 있는 시간이였고
중간중간 cs지식도 동시에 예시 이해를 통해 배울 수 있어서 유익했다
바로 이해한 내용을 코드로 작성하고 직접 웹페이지에 띄워보니 신기했다
이전에 배웠던 교육과는 확실히 다르다는 생각이 들었고
앞으로 매일매일 이렇게 지식을 쌓아나가면 엄청 성장할 수 있겠다는
자신감도 들었다!