Search
castle

jQuery

특성

js library

  • https://releases.jquery.com/
  • bootstrap과 비슷하게 <header><script> 삽입
  • 함수형 언어(lambda ) 형식 사용
    • $(...).<...>(function(){...})
  • http tag : <script></script> 안에 작성
  • $ : jQuery 문법 사용
  • $(<content>) : <content>에 해당하는 내용을 가져오며, 객체로 사용
    • # : id 영역
    • . : class 영역
    • $('#content') : id='content' 에 해당하는 data
    • $('#postAddBtn').click(function{...}) : 메소드를 사용해 이벤트 callback 함수 구현
  • this == self
# single_pages\templates\single_pages\landing.html

<script>
...
$(document).ready(function (){
...
$('#postList').empty();
...
success : function(data){
...
$(list).each(function(){
...
$('#postList').append(str);
...
error   : function(){
...
const post = {
...
title   : $('#title').val(),
...
author  : $('#author').val(),
...
$.ajax(
...
{
...
url         : "{% url 'blogAPI' %}",
...
type        : "POST",
...
</script>
  • $.ajax(...) : 자바 비동기 호출(ajax), rest api 호출
    • restreponse를 받아 실행
  • console → 디버깅
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Wel?come?</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <h1>page home</h1>
    <script>
        alert('jQuery alert msg')
        $(document).ready(function (){
            getPostList();
        })

        function getPostList(){
            $.ajax(
                {
                    url     : "{% url 'blogAPI' %}",
                    type    : "GET",
                    success : function(data){
		                    console.log(data);
                        alert("success 글 불러오기")
                    },
                    error   : function(){
                        alert("error 글 불러오기")
                    }
                }
            )

        }
    </script>
</body>
</html>

image.png


image.png


image.png

문법

  • 변수
재선언 재할당 변수의 스코프 변수 호이스팅
(변수를 선언하기 전에 참조가능 여부)      
var o o 함수 레벨 스코프
let x o 블록 레벨 스코프
const x x 블록 레벨 스코프
  • alert(<msg>) : 팝업창
  • $().empty() : context 전체 삭제
  • $(document).ready(...) : 문서 로드 완료 시 정의된 callback 함수 실행
  • $.ajax : 비동기 호출
  • success : 속성(이벤트 성공)
  • error : 속성(이벤트 실패)
  • $().val() : return value
  • $().val(<value>) : assign value
# single_pages\templates\single_pages\landing.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Wel?come?</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <h1>page home</h1>
    <script>
        // CSRF 토큰 가져오기 함수
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // 쿠키 이름 찾기
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        const csrftoken = getCookie('csrftoken');

        alert('jQuery alert msg');
        $(document).ready(function (){
            getPostList();
        });

        function getPostList(){
            $('#postList').empty();
            $.ajax(
                {
                    url     : "{% url 'blogAPI' %}",
                    type    : "GET",
                    success : function(data){
                        console.log(data);
                        let list = data;
                        $(list).each(function(){
                            console.log(this);
                            console.log("***");
                            let str = '';
                            str += '<div>';
                            str += this.title + "\n";
                            str += this.author + "\n";
                            str += this.content + "\n";
                            str += '</div>';
                            str += '<hr>';
                            $('#postList').append(str);
                            
                        })
                        alert("success 글 불러오기");
                    },
                    error   : function(){
                        alert("error 글 불러오기");
                    }
                }
            )
        };

        $(document).ready(function(){
            $('#postAddBtn').click(function(){
                const post = {
                    title   : $('#title').val(),
                    author  : $('#author').val(),
                    content : $('#content').val()
                };
                $.ajax(
                    {
                        url         : "{% url 'blogAPI' %}",
                        type        : "POST",
                        contentType : "application/json",
                        data        : JSON.stringify(post),
                        headers     : {'X-CSRFToken' : csrftoken},
                        success     : function(data){
                            console.log(data);
                            alert("글 삽입 성공");

                            $('#title').val('');
                            $('#author').val('');
                            $('#content').val('');
                            getPostList();
                        },
                        error       : function(xhr){
                            console.log(JSON.stringify(xhr.responseJSON));
                            alert("글 삽입 실패");
                        }
                    }
                )
            }
        );
        
    })

    </script>

    <h2>새 글 작 성</h2>
    <form id='postform'>
        <input type='text' id='title' placeholder='title' required><br>
        <input type='text' id='author' placeholder='author' required><br>
        <input type='text' id='content' placeholder='content' required><br>
        <input type='button' value='만들기' id='postAddBtn'>
    </form>

    <h2>글 목 록</h2>
    <div id="postList"></div>
</body>
</html>

image.png

left
right

C

Contents