Web

jQuery [lecture]

hololo 2019. 11. 21. 23:32

With jQuery

일반 Javascript만으로 Ajax를 하게되면 코딩량이 많아지고 브라우저별로 구현방법이 다른 단점이 있는데, jquery를 이용하면 더 적은 코딩량과 동일한 코딩방법으로 대부분의 브라우저에서 같은 동작을 할 수 있다.
jquery ajax를 사용하면, http get방식과 http post방식 모두를 사용하여 원격 서버로부터 데이터를 요청할 수 있다. Jquery는 ajax처럼 JavaScript의 라이브러리 중 하나인데 자바스크립틀를 좀 더 사용하기 쉽게 패키징화 시켜놓은 것이다.

- jQuery는 AJAX 기능을 위한 몇몇 함수들을 제공한다
- jQuery의 AJAX 함수들을 이용하면,
  - Http get과 post를 이용하여 remote server로 부터 text, html, xml, 또는 json을 요청할 수 있다
  - 웹 페이지에 몇몇 html 요소들로 외부 데이터를 로드할 수 있다

jQuery - Ajax load() method

 

- jQuery load() Method
: server에서 데이터를 가져오고, 돌아온 데이터를 선택된 요소에 넣는다

- Syntax
: $(selector).load(URL, data, callback);
URL = load하고 싶은 특정 URL을 적는다
data = 요청과 함께 전송할 쿼리 문자열 키/값 쌍 집합을 지정한다
callback = load()가 완료되기 전에 실행되는 함수의 이름

- file
<demo_test>
<h2>jQuery and AJAX is FUN!!</h2>
<p id="p1">This is some text in a paragraph.</p>

ex1) 특정 <div>에 "demo_test.txt"의 내용을 쓰기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});
</script>
</head>
<body>
 
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
 
<button>Get External Content</button>
 
</body>
</html>

ex2) demo_test.txt의 p1 내용을 div에 쓰기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt #p1");
  });
});
</script>
</head>
<body>
 
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
 
<button>Get External Content</button>
 
</body>
</html>

* 위와 다른점은 load("demo_test.txt #p1");

- callback option
다른 parameter들을 가질 수 있는데
  - responseTxt : call이 성공하면 결과내용을 포함 (위의 경우엔 demo_test.txt내용 포함)
  - statusTxt : call의 상태를 포함(success or error)
  - xhr : XMLHttpRequest object를 포함
ex)

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
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt"function(responseTxt, statusTxt, xhr){
    alert(responseTxt);
      if(statusTxt == "success")
        alert("External content loaded successfully!");
      if(statusTxt == "error")
        alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
  });
});
</script>
</head>
<body>
 
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
 
<button>Get External Content</button>
 
</body>
</html>

statusTxt==success

 

jQuery - AJAX get() and post() Methods

: jQuery get()과 post()는 HTTP GET이나 POST요청과 함께 서버에 데이터를 요청하기 위해 사용된다

1) jQuery $.get() Method
with an HTTP GET request
Syntax : $.get(URL, callback);
           URL = 요청하고 싶은 URL
           callback = 요청이 성공하면 실행될 함수 이름
ex)
<"demo_test.asp">
<%
response.write("This is some text from an external ASP file.")
%>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("demo_test.asp"function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>
 
<button>Send an HTTP GET request to a page and get the result back</button>
 
</body>
</html>
 

$get에서 첫번째 파라미터는 요청하고싶은 URL
           두번째 파라미터에서 callback의 첫번째 파라미터는 요청된 페이지의 내용, 두번째 파라미터는 요청결과를 가짐


2) jQuery $.post() Method
: with an HTTP POST request
Syntax : $.post(URL, data, callback);
           URL = 요청할 URL
           data = 요청과 함께 보낼 데이터들
           callback = 요청이 성공하면 실행될 함수의 이름