최신글
hyeonga_code
Ajax_XMLHttpRequest 모듈 만들기 본문
반응형
'httpRequest.js' javascript 파일 생성하기
=====
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
|
/**
*
*/
// XMLHttpRequest 객체를 생성하기 위한 함수입니다.
function getXMLHttpRequest() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) { return null; }
}
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return null;
}
}
// XMLHttpRequest 객체를 저장하기 위한 전역 변수를 선언합니다.
var httpRequest = null;
// Ajax 요청을 보내기 위한 함수입니다.
function sendRequest(url, params, callback, method) {
/*
- url : 요청을 보낼 주소
- params : 요청에 포함될 매개 변수(POST 요청 시 사용)
- callback : 요청이 완료되면 호출할 함수
- method : 요청 메소드(GET/POST_기본값)
*/
// XMLHttpRequest 객체 생성
httpRequest = getXMLHttpRequest();
// method값이 지정되지 않는 경우 get이 기본값입니다.
var httpMethod = method ? method : 'GET';
// 둘 다 아닌 경우 get으로 설정합니다.
if (httpMethod != 'GET' && httpMethod != 'POST') {
httpMethod = 'GET';
}
// 포함될 매개 변수를 설정합니다.
var httpParams = (params == null || params == '') ? null : params;
var httpUrl = url;
// get 방식으로 넘어온 매개 변수가 있는 경우
if (httpMethod == 'GET' && httpParams != null) {
httpUrl = httpUrl + "?" + httpParams;
}
// 객체를 초기화 하고 요청 메소드, URL을 설정합니다. true: 비동기 요청
httpRequest.open(httpMethod, httpUrl, true);
// header에 content-type을 지정합니다.
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = callback;
// post인 경우 넘어온 값을 지정합니다.
httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}
|
- 반복되는 작업을 모듈로 작성하여 모든 Ajax를 처리할 수 있습니다.
반응형