Ajax 호출의 일반적인 패턴

2007. 8. 21. 13:58Programming/JavaScript

서핑 중 기본적인 Ajax 패턴을 상당히 간결하게 짜 놓았길래 담습니다.

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.