본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/JQuery

jquery에서 ajax 사용 메소드 [ get(), post(), ajax(), load() ]

by 차누감 2019. 12. 18.

<최종 화면> 한 웹페이지에서 여러가지 방식을 사용해보자.


jquery에서 ajax사용하는 메소드를 알아보자.

우선 4개의 버튼과 textarea 1개를 만들자.

우선 get() 메소드를 알아보자. text.txt는 이미 만들었다.

(같은 저장된 폴더에)

확인을 위해 서버에 업로드 하자.

div에도 표시할 수 있다. 

get메소드를 이용해서 GET방식으로 데이터를 보낼 수 있다.

아래 사진과 같이 php파일을 (같은 저장된 폴더에) 만들었다.

확인을 위해 서버에 업로드를 하고 실행하자.

이번엔 post메소드로 POST방식으로 데이터를 보내보자.

ajax(GET, POST 방식) 메소드를 이용해보자.

load 메소드를 이용해서 html 내용을 가져오자.

변경된 사항이 있으니, 다시 서버에 업로드를 하고 확인하자.

<최종 화면>

이제 버튼 하나씩 눌러서 확인해보자.

만약 load Method 버튼을 눌러서 특정 요소만 가져오고 싶다면? textarea만 가져오겠다.


07_ajax_jquery.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
 
    <!-- JQuery 추가 -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
    <script>
        $(document).ready(function(){ //body의 작업이 끝나면 실행
 
        // jquery에서 ajax기술을 위해 만든 4개의 메소드
        // 1) get()
        $('#b1').click(function(){
 
            // get메소드 수행
            $.get('text.txt'function(data, status){
                $('#ta').val(data+"\n\n STATUS :  "+status);
            });
 
            $.get('getTest.php?name=sam&pw=1234'function(data, status){
                $('#target').html(data);
            });
        });
 
        // 2) post()
        $('#b2').click(function(){
 
            $.post('text.txt'function(data,status){
                $('#ta').val(data);
            });
 
            $.post('postTest.php', {name:"robin",pw:"5678"},function(data, status){
                $('#target').html(data);
            });
        });
 
        // 3) ajax()
          $('#b3').click(function(){
            // ajax()에 {}객체 1개 전달
            $.ajax({
                type:"GET",
                url: "text.txt",
                success: function(data,status){ //status는 생략해도 됨
                    $('#ta').val(data);
                },
                error: function(error){
                    $('#ta').val(error.responseText); 
                }
            });
 
            $.ajax({
                type:"POST",
                url: "postTest.php",
                data: "name=hong$pw=4567",
                success: function(data,status){ //status는 생략해도 됨
                    $('#ta').val(data);
                },
                error: function(error){
                    $('#ta').val(error.responseText); 
                }
            });
            
        });
 
        // 4) load()
        $('#b4').click(function(){
            $('#ta').load('text.txt'); //get방식으로 읽어서 ta에 값을 넣음
 
            // HTML문법을 그대로 가져옴.
            $('#target').load('05_noAjax.html #ta');
 
        });
 
    });
     
    </script>
 
</head>
<body>
 
    <p>
        <button id="b1">get Method</button>
        <button id="b2">post Method</button>
        <button id="b3">ajax Method</button>
        <button id="b4">load Method</button>
    </p>
    <hr>
    <textarea id="ta" cols="30" rows="5"></textarea>
    <div id="target"></div>
    
</body>
</html>
 
 

text.txt

1
2
3
4
5
Hello world!!
 
Nice to meet you.
 
안녕하세요.

postText.php

1
2
3
4
5
6
7
8
9
<?php
 
    header('Content-Type:text/html; charset=utf-8');
 
    $name= $_POST['name'];
    $pw= $_POST['pw'];
 
    echo "$name $pw";
?>
 

05_noAjax,php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
 
    header('Content-Type:text/html; charset=utf-8');
 
    $name= $_GET['name'];
    $email= $_GET['email'];
 
    //원래는 받은 데이터를 DB에 저장해야 하지만.. 시간상 생략
    // echo "$name $email 이 등록되었습니다.";
 
    // 그전에 보여지던 05_noAjax.html문서가 사라져버리기 때문에
    // 입력폼 모양 페이지가 없어져 버리고 echo된 문자열만 보이게 됨.
 
    // 이게 싫다면...
    echo ("
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset='UTF-8'>
            <title></title>
        </head>
        <body>
 
            <h3>회원가입 페이지</h3>
 
            <form action='05_noAjax.php' method='GET'>
                <input type='text' name='name' value='$name'>
                <input type='text' name='email'value='$email'>
 
                <input type='submit'>
            </form>
            <hr>
            <textarea id='ta' cols='30' rows='3'>$name #email 이 등록되었습니다.</textarea>
            
        </body>
    </html>
    ");
?>
 
 

 

댓글