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.
'Development > JavaScript' 카테고리의 다른 글
| HTML WYSIWYG Editor를 만들기 위한 기본적인 사용법 (0) | 2007.08.23 |
|---|---|
| HTTP Cookie Javascript (0) | 2007.08.23 |
| ASP.NET에서 사용할 정말 편한 Ajax Library (2) | 2007.08.18 |
| Ajax로 데이터 출력을 위한 Javascript Paging 소스 (2) | 2007.08.17 |
| 파일업로드 이미지 미리보기 자바스크립트 (2) | 2007.08.14 |