본문 바로가기

웹 프로그래밍/jQuery

[jQuery] sendProcess를 쉽게 사용: $.ajax();

아래는 자바스크립트 문법으로 만든 sendProcess 메소드다.

그러나, jQuery를 활용하면 매우 쉽게 이 기능을 사용할 수 있다.

let httpRequest = null;

function getXMLHttpRequest() {
	if(window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}
	if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function sendProcess(method, url, params, callback) {
	// 1. request 객체 생성
	httpRequest = getXMLHttpRequest();
	
	// 2. callback 함수 정의
	httpRequest.onreadystatechange = callback;
	
	// method 초기값 설정
	let httpMethod = method.toUpperCase();
	if(httpMethod != 'GET' && httpMethod != 'POST')
		httpMethod = 'GET';

	// parameter 설정 : json 형태로 넘어 올 수 있으니, httpParams 라는 변수를 별도로 만든다.
	httpParams = params;
	if(params == null || params == '')
		httpParams = '';
	
	if(typeof(httpParams) == 'object'){
		// json 형태로 들어올 경우, 파라미터를 초기화하고, name=value 형태로 변환한다.
		// json to 'name=value&name=value'
		httpParams = '';
		for(let key in params){
			if(httpParams != '')
				httpParams += '&'
			httpParams += key + "=" + encodeURIComponent(params[key]);
			console.log(httpParams);
			
		}
		
		
	}
	
	
	// 3. 메소드에 맞게 초기화하여 전송
	httpUrl = url;
	if(httpMethod == 'GET' && httpParams != ''){
		httpUrl = url + '?' + httpParams;
	} 
	
	httpRequest.open(httpMethod, httpUrl, true);
	if(httpMethod == 'POST'){
		httpRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
	}
	
	// 3항 연산자 활용하여 전송
	httpRequest.send(httpMethod == 'GET' ? null : httpParams);
	
}

 

아래처럼 $.ajax 이용해서 POST, GET 방식 둘 다 쉽게 쓸 수 있다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

	//param3.jsp?name=hong&age=25
	$(document).ready(function(){
		$('button').click(function(){
			
			let name = $('#name').val(); //document.getElementById('name').value
			let age = $('#age').val();
			
			$.ajax({
				url : 'param3.jsp',
				type : 'get',
				// type : 'post',
				
				// data : 'name=hong&age=265',
				// 아래는 JSON 형태. 훨씬 간편하다.
				data : { 
					name : name,
					age : age
				},
				success : function(result){
					console.log(result)
					$('#debug').val(result)
				}, error : function(error){
					$('#debug').val('오류코드 : ' + error.status + '\n')
				}
			})
		})
	})
	
</script>
</head>
<body>
	<textarea rows="10" cols="80" id ="debug"></textarea><br>
	이름 : <input type ="text" name = "name" id = "name"><br>
	나이 : <input type ="text" name = "age" id = "age"><br>
	<button>호출</button>
</body>
</html>

그러나, post, get 방식을 분리할 수도 있다.

$.ajax가 아닌, $.post 나 $.get은 파라미터 방식을 쓴다.

 

			$.post('param3.jsp', {'name': name, 'age': age}, function(result) {
				$('#debug').val(result)
			})
			
			/*
			$.post('param3.jsp', "name=hong&age=30", function(result) {
				$('#debug').val(result)
			})
			*/
			
			/*
			$.post('param3.jsp', function(result) {
				$('#debug').val(result)
			})
			*/

 


전체 코드

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

	//param3.jsp?name=hong&age=25
	$(document).ready(function(){
		$('button').click(function(){
			
			let name = $('#name').val(); //document.getElementById('name').value
			let age = $('#age').val();
			
			
			// $.ajax가 아닌, $.post 나 $.get은 파라미터 방식을 쓴다.			
			$.post('param3.jsp', {'name': name, 'age': age}, function(result) {
				$('#debug').val(result)
			})
			
			/*
			$.post('param3.jsp', "name=hong&age=30", function(result) {
				$('#debug').val(result)
			})
			*/
			
			/*
			$.post('param3.jsp', function(result) {
				$('#debug').val(result)
			})
			*/
			
			
			
			
			/* $.ajax({
				url : 'param3.jsp',
				type : 'get',
				// type : 'post',
				
				// data : 'name=hong&age=265',
				// 아래는 JSON 형태. 훨씬 간편하다.
				data : { 
					name : name,
					age : age
				},
				success : function(result){
					console.log(result)
					$('#debug').val(result)
				}, error : function(error){
					$('#debug').val('오류코드 : ' + error.status + '\n')
				}
			}) */
		})
	})
	
</script>
</head>
<body>
	<textarea rows="10" cols="80" id ="debug"></textarea><br>
	이름 : <input type ="text" name = "name" id = "name"><br>
	나이 : <input type ="text" name = "age" id = "age"><br>
	<button>호출</button>
</body>
</html>