Jquery,ajax

서샘이·2022년 1월 5일
0

2주차 코딩 수업
1. Jquery
jquery 는 javascript를 미리 작성해둔 것, 라이브러리.

1) input 박스의 값 가져오기

  • id값 입력 후 val()로 값을 가져옴.
    $('#id').val();

2) div 보이기/숨기기

  • 보이기 (=css의 display : none;)
    $('#id').show();
  • 숨기기 (=css의 display : block;)
    $('#id').hide();

3) 태그 내 텍스트 입력
(1) input box의 경우
$('#id').val('텍스트 입력하면 됨!');

(2) 다른 것들 - ex) 버튼 텍스트
$('#id').text('버튼 누르기');

4) 태그 내 html 입력

  • 버튼 넣기
    let temp_html = <button>추가 버튼!</button>;
    $('#id').append(temp_html);

5) 포스팅 박스 열기 버튼에 function 달기

//onclick 속성
포스팅박스 열기

(1) 클릭으로 포스팅 박스 여닫기

  • 포스팅 박스에 id값 주기
  • 포스팅 박스 제어 ex) id="post-box"
    function openclose() {
    if($('#post-box').css('display')=='block') {
    $('#post-box').hide();
    } else {
    $('#post-box').show);
    }
    }
    * post box 시작부터 감추려면 css의 display: none;

(2) '포스팅박스 열기' 버튼의 글씨 바꾸기

  • 포스팅 박스 열기 버튼에 id값 주기
  • 버튼 텍스트 바꾸기
    function openclose() {
    if($('#post-box').css('display')== 'block') {
    $('#post-box').hide();
    $('#post-box').text('포스팅박스 열기');
    } else {
    $('#post-box').show();
    $('#post-box').text('포스팅박스 닫기');
    }
    }

6) Quiz1.
(1) input-q1의 입력값 가져오기
(2) 입력칸 빈칸이면 경고메세지 아니면 입력값 띄우기

function q1() {
let value = $('#input-q1').val();
if (value == '') {
alert('입력하세요!');
} else {
alert(value);
}
}
Quiz2.
(1) input-q2의 입력값 가져오기
(2) 값에 @가 있으면 도메인만 추출 ex. abc@defg.hij 중 defg만 추출해 alert 띄우기
(3) 이메일이 아닐 경우 '이메일이 아닙니다.' alert 띄우기

funtion q2() {
let email = $('#input-q2').val();
if(email.includes('@')) {
let domain = email.split('@')[1].split('.')[0];
alert(domain);
} else {
alert('이메일이 아닙니다!');
}
}
Quiz3.
(1) input-q3의 값 가져오기
(2) 값을 이용해 names-q3에 붙일 태그 만들기.
(3) 만들어둔 temp_html을 names-q3에 붙이고 내부 태그는 모두 비움

function q3() {
let name = ('#input-q3').val(); if(name == '') { alert('이름을 입력하세요') return; } let temp_html = `<li>{name}`;
$('#names-q3').append(temp_html);
}
function q3_remove() {
$('#names-q3').empty();
}

  1. ajax
    1) 기본 골격
    $.ajax({
    type: "GET", - GET 방식 요청
    url: "url입력",
    data: {}, - 요청하면서 함께 줄 데이터 (GET 요청 시 비움)
    success: function(response) { - 서버에서 준 결과를 response 라는 변수에 담음
    console.log(response)
    }
    })
  • GET, url 뒤에 주소를 붙여 데이터를 가짐
    POST, data: {}에 넣어서 데이터를 가짐
    ex) data: {param: 'value',param2:'value2'},
    2) 연습

    3) 연습 2

    <script>
     function q1() {
       $.ajax({
           type: "GET",
           url: "https://api.thecatapi.com/v1/images/search",
           data: {},
           success: function (response){
              let imgurl = response[0]['url']
               $("#img-cat").attr("src",imgurl)
                  }
             })
      }
    </script>

    4) 연습 3

     <script>
        function q1() {
            $('#names-q1').empty()
            $.ajax({
               type: "GET",
               url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
               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 > 70) {
                     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>

    5) 로딩 후 호출

    $(ducument).ready(function() {
    alert('로딩 끝!')
    });

    ex)

    $(ducument).ready(function() {
      get_rate();

    });

    function get_rate() {
    $.ajax({
    type: "GET",
    url: "url입력",
    data: {},
    success: function (response) {
    let now_rate = response['rate'];
    $('#now_rate').text(now_rate);
    }
    })
    }

2주차 여전히 배움의 즐거움 가득이다.
다음주도 그러길 바라며...코딩력 + 1

0개의 댓글