JQuery / Ajax

hihyeon_cho·2022년 10월 21일
1

sparta-web

목록 보기
3/8

JQuery

Javascript를 미리 작성해 둔 라이브러리
Javascript 보다 비교적 간단히 코드를 작성할 수 있다.
import 필수 !

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

JQuery 코드 연습하기

  • value 값 넣기
    $(‘#url’).val(‘...')
  • value 값 가져오기
    $(‘#url’).val()
  • div( id ="box") 숨기기
    $('#box').hide()
  • div( id ="box")나타내기
    $('#box').show()
  • 내용 추가하기
// let 선언으로 문자열 추가
let temp_html = `<button id="btn">버튼</button>`
// 추가한 내용 html화
$(‘#btn’).append(temp_html)
  • 지정해서 바꾸기
    ex) #box안에 있는 h1 바꾸기
let title = ‘제목’
let temp_html = `<h1>${title}</h1>`
$(‘#box’).append(temp_html)
  • 지우기
$('#box').empty()
  • 빈칸이면 "입력하세요" 띄우기
function test1{
    let txt = $('#inputTxt').val()
    if (txt == '') {
        alert('입력하세요')
        }
      }

Ajax 사용하기

Ajax :

Ajax란 비동기 자바스크립트와 XML (Asynchronous JavaScript And XML)을 말합니다. 간단히 말하면, 서버와 통신하기 위해 XMLHttpRequest 객체를 사용하는 것을 말합니다.
Ajax를 이용하면 페이지 새로고침 없이 서버에 요청하고 서버로부터 데이터를 받아 작업을 수행하는 것이 가능합니다.

JQuery를 import한 페이지에서만 동작가능

Ajax 코드 기본골격

$.ajax({
  type: "GET", 
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {}, 
  success: function(response){ 
    console.log(response)
  }
})

data :
GET 요청시에는 url뒤에 붙여서 데이터를 가져가야 하기 때문에 비워두어야 하며,
POST 요청시에는

data{id:'value', id2:'value2'},

의 형식의로 데이터를 가져간다.

< 숙제리뷰 >
날씨API로 페이지에 온도를 나타내는 과제

  • html
<p>현재기온 : <span id="temp">00.0</span></p>

00.0이 온도로 바뀌어야하는데, 숫자뒤에 붙어서
.empty를 사용해서 span을 비운 후 들어갈 수 있도록
코드를 작성했었다.

success: function(response){ 
    let temp = response['temp']
    let temp_html = `${temp}`
    $('#temp').empty()
    $('#temp’).append(temp_html)
  }

답을 확인해보니 이렇게 길게 쓸 필요가 없이
.text를 사용하면 되는 거였다.

success: function(response){ 
    let temp = response['temp']
	$('#temp').text(temp)
  }

.text( ) 는?
선택한 요소 안의 내용을 가져오거나, 다른 내용으로 바꾼다.
찾아보니 .html( )도 같은 역할이었다.
차이점은
.html( )문자열과 태그 구분없이 모두 가져오는 것이고,
.text( )문자열만 가져오는 것이다.

profile
코딩은 짜릿해 늘 새로워 ✨

0개의 댓글