[jQuery] Ajax 사용예제
jQuery란?
jQuery는 빠르고 작고 기능이 풍부한 JavaScript 라이브러리입니다. 여러 브라우저에서 작동하는 사용하기 쉬운 API를 사용하여 HTML 문서 탐색 및 조작, 이벤트 처리, 애니메이션 및 Ajax와 같은 작업을 훨씬 더 간단하게 만듭니다. 다목적성과 확장성의 조합으로 jQuery는 수백만 명의 사람들이 JavaScript를 작성하는 방식을 변화시켰습니다.
jQuery의 특징과 장점
이렇게 수많은 자바스크립트 라이브러리 중에서도 jQuery가 특히 많이 사용되는 이유는 다음과 같다.
- jQuery는 주요 웹 브라우저의 구버전을 포함한 대부분의 브라우저에서 지원된다.
- HTML DOM을 손쉽게 조작할 수 있으며, CSS 스타일도 간단히 적용할 수 있다.
- 애니메이션 효과나 대화형 처리를 간단하게 적용해 준다.
- 같은 동작을 하는 프로그램을 더욱 짧은 코드로 구현할 수 있다.
- 다양한 플러그인과 참고할 수 있는 문서가 많이 존재한다.
- 오픈 라이선스를 적용하여 누구나 자유롭게 사용할 수 있다.
jQuery 적용하기
jQuery 사용하기 위해서는 jQuery를 import 해야한다.
jQuery 파일을 다운로드 받아서 파일형태로 import를 해도 좋고, 아래 CDN 을 이용해도 좋다.
jQuery 다운로드
Download jQuery | jQuery
link Downloading jQuery Compressed and uncompressed copies of jQuery files are available. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production. You can also download
jquery.com
구글 CDN 사용하기
3.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
1.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Ajax란?
Ajax란 Asynchronous JavaScript and XML을 의미한다.
Ajax는 JavaScript와 XML을 이용한 비동기적 정보 교환 기법이다.
Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있게 해준다. Ajax는 백그라운드 영역에서 서버와 데이터를 교환하여 웹 페이지에 표시 및 데이터를 로딩해 준다.
Ajax Method
이러한 메소드는 더 적은 코드로 보다 일반적인 유형의 Ajax 요청을 수행합니다.
jQuery.get()
HTTP GET 요청을 사용하여 서버에서 데이터를 로드합니다.
jQuery.getJSON()
GET HTTP 요청을 사용하여 서버에서 JSON 인코딩 데이터를 로드합니다.
jQuery.getScript()
GET HTTP 요청을 사용하여 서버에서 JavaScript 파일을 로드한 다음 실행합니다.
jQuery.post()
HTTP POST 요청을 사용하여 서버에 데이터를 보냅니다.
.load()
서버에서 데이터를 로드하고 반환된 HTML을 일치하는 요소에 배치합니다.
참고링크 : https://api.jquery.com/category/ajax/shorthand-methods/
Shorthand Methods | jQuery API Documentation
Load data from the server using a HTTP GET request. Load JSON-encoded data from the server using a GET HTTP request. Load a JavaScript file from the server using a GET HTTP request, then execute it. Send data to the server using a HTTP POST request. Load d
api.jquery.com
Ajax 예제
1. ajax_test.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="http://localhost/ppomi/bootstrap-3.3.2-dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
<script src="http://localhost/ppomi/bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>
<script>
$(function() {
$("#requestBtn").on("click", function() {
var params = {
name : "홍길동"
, sex : "남자"
, age : "20"
, tellPh : "010-0000-0000"
}
$.ajax({
url: "ajaxProc.php", //클라이언트가 HTTP 요청을 보낼 서버의 URL 주소
data: params, // HTTP 요청과 함께 서버로 보낼 데이터
method: "GET", // HTTP 요청 메소드(GET, POST 등)
dataType: "json", // 서버에서 보내줄 데이터의 타입
})
// HTTP 요청이 성공하면 요청한 데이터가 done() 메소드로 전달됨
.done(function(json) {
$("#text").text(json.name +", "+ json.family +", "+ json.age +", "+ json.weight).appendTo("body");
alert("요청 성공");
})
// HTTP 요청이 실패하면 오류와 상태에 관한 정보가 fail() 메소드로 전달됨
.fail(function(xhr, status, errorThrown) {
$("#text").html("오류가 발생했습니다.<br>")
.append("오류명: " + errorThrown + "<br>")
.append("상태: " + status);
})
//HTTP 요청이 성공하거나 실패하는 것에 상관없이 언제나 always() 메소드가 실행됨
.always(function(xhr, status) {
alert("요청 완료");
});
});
});
</script>
</head>
<body>
이름 : <input type="text" id="name" value="홍길동"><br/>
성 : <input type="text" id="sex" value="여자"><br/>
나이 : <input type="text" id="age" value="20"><br/>
전화번호 : <input type="text" id="tellPh" value="010-0000-0000"><br/>
<input type="button" id="requestBtn" value="확인"><br/><br/>
<p id="text"></p>
<h1>결과</h1>
</body>
</html>
참고링크