스파르타코딩 내일배움단4

한재창·2022년 10월 20일
0

4일차

jQuery

i) HTML의 요소들을 조작할 수 있게 Javascript를 미리 작성해둔 라이브러리
ii) Javascript보다 직관적이고 짧아 보기 편리함

// javascript
document.getElementById("element").style.display = "none";
// jQuery
$("#element").hide(); // id가 element인 것을 숨김

iii) jQuery를 사용하려면 링크를 임포트 해줘야 함

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>

iv) 문자열을 HTML화 시켜줄 수 있음

let temp_html = `<button>눌러주세요</button>` // 백틱을 써야함
$("#element").append(temp_html) // HTML화 시켜주는 코드

- 연습

  1. 박스 열고 닫기
<!doctype html>
<html lang="en">

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<title>스파르타 피디아</title>


<style>
.my-box {
display: none;
}

</style>
<script>
function open_box(){
$('#post-box').show()
} // 박스를 열어주는 이벤트
function close_box(){
$('#post-box').hide()
} // 박스를 숨겨주는 이벤트
</script>
</head>

<body>
<div class="my-title">
<h1>내 생애 최고의 영화들</h1>
<button onclick="open_box()">영화 기록하기</button> // 열어주는 이벤트 설정
</div>
<div class="my-box">
<button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button> // 닫아주는 이벤트 설정
</div>
</body>

</html>
  1. 전체 연습
<!doctype html>
<html lang="ko">

<head>
<meta charset="UTF-8">
<title>jQuery 연습하고 가기!</title>

<!-- JQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
</style>

<script>
function q1() {
    const val1 = $("#input-q1").val(); // input-q1 입력값을 가져와 변수에 저장
    if (val1 === "") {
        alert("입력하세요!"); // #(id)input-q1가 빈칸일 때
    } else {
        alert(val1); // 빈칸이 아닐 때
    }
}

function q2() {
    const val2= $("#input-q2").val(); input-q2 입력값을 가져와 변수에 저장
   // val2.includes("@") :
   // 변수 val2 값에 abcwockd95@naver.com 라고 입력했을 때 "@"가 있으므로 true
   // abcwockd95 라고 입력했을 때 "@"가 없으므로 false를 반환함
   if ( val2.includes("@") === true) {
        alert(val2.split("@")[1].split(".")[0]);
      } // val2.split("@")[1] = naver.com
      	// (naver.com).split(".")[0] = naver		
      else if ( val2.includes("@") === false ) {
        alert("이메일이 아닙니다.");
    }
}

function q3() {
$('...').append(temp_html)을 이용하면 굿!)
    const val3 = $("#input-q3").val(); // input-q3 입력값을 가져와 변수에 저장
    let temp_html = `<li>${val3}</li>`
    $("#names-q3").append(temp_html); // temp_html을 names-q3에 붙임
}

function q3_remove() {
    $("#names-q3").empty(); // 내부 태그를 모두 삭제
}

</script>

</head>

<body>
<h1>jQuery + Javascript의 조합을 연습하자!</h1>

<div class="question-box">
<h2>1. 빈칸 체크 함수 만들기</h2>
<h5>1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기</h5>
<h5>[완성본]1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기</h5>
<input id="input-q1" type="text" /> <button onclick="q1()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>2. 이메일 판별 함수 만들기</h2>
<h5>2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기</h5>
<h5>2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기</h5>
<h5>[완성본]2-3. 이메일 도메인만 얼럿 띄우기</h5>
<input id="input-q2" type="text" /> <button onclick="q2()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>3. HTML 붙이기/지우기 연습</h2>
<h5>3-1. 이름을 입력하면 아래 나오게 하기</h5>
<h5>[완성본]3-2. 다지우기 버튼을 만들기</h5>
<input id="input-q3" type="text" placeholder="여기에 이름을 입력" />
<button onclick="q3()">이름 붙이기</button>
<button onclick="q3_remove()">다지우기</button>
<ul id="names-q3">
<li>세종대왕</li>
<li>임꺽정</li>
</ul>
</div>
</body>

</html>

서버, 클라이언트 통신

i) API : 정의 및 프로토콜 집합을 사용하여 두 소프트웨어 구성 요소가 서로 통신할 수 있게 하는 메커니즘 즉 컴퓨터나 컴퓨터 프로그램 사이의 연결을 뜻함
ii) 클라이언트가 요청 할 때 "타입"이라는 것이 존재함
iii) GET : 데이터 조회(Read)를 요청할 때
ex) 영화 목록 조회 등
GET 방식으로 데이터 전달하는 방법
https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967
? 기준으로 앞부분이 <서버 주소>, 뒷부분이 <영화 번호>
? : 여기서부터 전달할 데이터가 작성된다는 의미
& : 전달할 데이터가 더 있다는 의미
iv) POST : 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청할 때
ex) 회원가입, 회원탈퇴, 비밀번호 수정 등

-Ajax

  1. Ajax는 jQuery를 임포트한 페이지에서만 동작 가능
  2. 연습
$.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"]
}
})
<!doctype html>
<html lang="ko">

<head>
<meta charset="UTF-8">
<title>jQuery 연습하고 가기!</title>

<!-- jQuery를 import 합니다 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}

.good {
    color : green;
}
</style>

<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 tmep_html = `` // 빈 문자열을 만들어 놓는다.

          if (gu_mise < 30) {
              tmep_html = `<li class="good">${gu_name} : ${gu_mise}</li>` // 30이하면 let temp_html 값
          } else {
              tmep_html = `<li>${gu_name} : ${gu_mise}</li>` // 30이하가 아니면 let temp_html 값
          }

          $("#names-q1").append(tmep_html);
      }
    }
  })
}
</script>

</head>

<body>
<h1>jQuery+Ajax의 조합을 연습하자!</h1>

<hr />

<div class="question-box">
<h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
<p>모든 구의 미세먼지를 표기해주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">업데이트</button>
<ul id="names-q1">
</ul>
</div>
</body>

</html>
profile
취준 개발자

0개의 댓글

관련 채용 정보