Ajax 호출의 일반적인 패턴
글 작성자: 써니루루
서핑 중 기본적인 Ajax 패턴을 상당히 간결하게 짜 놓았길래 담습니다.
XHR을 생성해서 반환하는 구문을 상당히 간결하게 잘 처리했네요 ㅎㅎ
XMLHttpRequest functions
Ref URI : http://www.quirksmode.org/js/xmlhttp.html
XHR을 생성해서 반환하는 구문을 상당히 간결하게 잘 처리했네요 ㅎㅎ
XMLHttpRequest functions
Ref URI : http://www.quirksmode.org/js/xmlhttp.html
function sendRequest(url,callback,postData) { var req = createXMLHTTPObject(); if (!req) return; var method = (postData) ? "POST" : "GET"; req.open(method,url,true); req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if (postData) req.setRequestHeader('Content-type','application/x-www-form-urlencoded'); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { // alert('HTTP error ' + req.status); return; } callback(req); } if (req.readyState == 4) return; req.send(postData); } var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }
It's used like this:
sendRequest('file.txt',handleRequest);
Now the file file.txt
is fetched, and when that's done the function handleRequest()
is called. This function receives the XMLHttpRequest object as an argument, which I traditionally call req
(though, of course, you can use any variable name you like). Typically, this function reads out the responseXML
or responseText
and does something with it.
function handleRequest(req) { var writeroot = [some element]; writeroot.innerHTML = req.responseText; }
One object per request
This function creates a new XMLHttpRequest object for every request you make. In simple cases such as this site, where every page fetches only three to five files, I don't mind creating three to five objects. In more complex sites, however, where any page can make an arbitrary amount of requests, it's probably better to write a function that reuses existing XMLHttpRequest objects.
댓글
이 글 공유하기
다른 글
-
HTML WYSIWYG Editor를 만들기 위한 기본적인 사용법
HTML WYSIWYG Editor를 만들기 위한 기본적인 사용법
2007.08.23 -
HTTP Cookie Javascript
HTTP Cookie Javascript
2007.08.23 -
ASP.NET에서 사용할 정말 편한 Ajax Library
ASP.NET에서 사용할 정말 편한 Ajax Library
2007.08.18 -
Ajax로 데이터 출력을 위한 Javascript Paging 소스
Ajax로 데이터 출력을 위한 Javascript Paging 소스
2007.08.17