mozilla

Revision 176344 of Ajax 시작하기

  • 리비전 슬러그: AJAX/Getting_Started
  • 리비전 제목: Ajax 시작하기
  • 리비전 아이디: 176344
  • 제작일시:
  • 만든이: Yongsuhb.e
  • 현재 리비전인가요? 아니오
  • 댓글 /* 1단계 – say "Please!" or How to Make an HTTP Request */
태그: 

리비전 내용

breadcrumbs /breadcrumbs

This article guides you through the AJAX basics and gives you two simple hands-on examples to get you started.

AJAX란?

AJAX (Asynchronous JavaScript and XML)는 수년전부터 두개의 강력한 브라우져에 의해 새로 만들어진 용어입니다. 하지만 최근 Gmail, Google의 추천검색어, 그리고 Google 지도가 나오기전까지 많은 개발자들은 그냥 보고 지나쳤죠.

질문할 수 있는 두가지 특징 :

  • 웹 페이지를 리로딩(reloading)하지않고 서버에 리퀘스트(request)할수 있음.
  • XML문서로 작업을 하거나 파싱할 수 있음.

1단계 – say "Please!" or How to Make an HTTP Request

자바스크립트를 사용해서 서버에 HTTP request를 하기위해서, 이런기능을 제공하는 클레스 인스턴스가 필요합니다. 그런 클레스는 인터넷익스플로러(Internet Explorer)에서 최초로 XMLHTTP라고 불리우는 엑티브엑스(ActiveX)로 도입되었습니다. 모질라(Mozilla), 사파리(Safari)그리고 다른 브라우져에서는 마이크로소프트의 엑티브엑스 오브젝트의 특성과 메소드를 지원하기위해 XMLHttpRequest클레스를 제공합니다.

결국, 모든브라우져에서 사용할 수 있는 인스턴스를 만들기 위해서는 아래와 같이 하십시오.

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
}

(기술을 목적으로 하기 때문에 위의 예는 XMLHTTP인트턴스를 만드는데 사용된 코드는 약간 간단화 되어 있습니다. 실제 사용예를 보려면 위 문서의 단계3을 보십시오.)

서버에서 응답이 XML mime-type 헤더가 아닐경우 어떤 모질라 브라우져에서는 잘 작동하지 않을 수 있습니다. mimetype을 만족시키기위해, 서버로 부터 받은 헤더가 text/xml이 아닐경우 오버라이드하기 위한 다른 메소드로 해결 할 수 있습니다.

http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');

요구(request)에 의해서 서버로부터 받은 내용을 어떻게 할것인가를 결정하는것이 다음에 할 일입니다. 이번 단계에서는 자바스크립트로 서버로부터 받은 응답을 처리하는 HTTP request에 대해 말할 필요가 있습니다. 이것은 아래와 같은 당신이 사용하고 싶은 자바스크립트 함수 이름(nameOfTheFunction)을 onreadystatechange 프로퍼티로 설정하면 됩니다. :

http_request.onreadystatechange = nameOfTheFunction;

함수 이름뒤에 괄호와 넘어갈 파라미터가 없습니다. Also, instead of giving a function name, you can use the Javascript technique of defining functions on the fly and define the actions that will process the response right away, like this:

http_request.onreadystatechange = function(){
    // do the thing
};

Next, after you've declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the open() and send() methods of the HTTP request class, like this:

http_request.open('GET', 'http://www.example.org/some.file', true);
http_request.send(null);
  • The first parameter of the call to open() is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs
  • The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a 'permission denied' error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.
  • The third parameter sets whether the request is asynchronous. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.

The parameter to the send() method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:

name=value&anothername=othervalue&so=on

Note that if you want to POST data, you have to change the MIME type of the request using the following line:

http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Otherwise, the server will discard the POSTed data.

Step 2 – "There you go!" or Handling the Server Response

Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.

http_request.onreadystatechange = nameOfTheFunction;

Let's see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it's OK for you to continue processing it.

if (http_request.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}

The full list of the readyState values is as follows:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)

(Source)

The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the W3C site. For our purposes we are only interested in 200 OK response.

if (http_request.status == 200) {
    // perfect!
} else {
    // there was a problem with the request,
    // for example the response may be a 404 (Not Found)
    // or 500 (Internal Server Error) response codes
}

Now after you've checked the state of the request and the HTTP status code of the response, it's up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:

  • http_request.responseText – will return the server response as a string of text
  • http_request.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Step 3 – "All together now!" - A Simple Example

Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." and then we'll alert() the contents of the test.html file.

<script type="text/javascript" language="javascript">

    

    function makeRequest(url) {

        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
</script>
<span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')">
        Make a request
</span>


In this example:

  • The user clicks the link "Make a request" in the browser;
  • This calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

You can test the example here and you can see the test file here.

Note: The line http_request.overrideMimeType('text/xml'); above will cause Javascript Console errors in Firefox 1.5b as documented at https://bugzilla.mozilla.org/show_bug.cgi?id=311724 if the page called by XMLHttpRequest is not valid XML (eg, if it is plain text).

If you get Syntax Error or Not Well Formed Error on that browser, and you're not trying to load an XML page from XMLHttpRequest, remove that line from your code.

Note 2: if you are sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. If you do not set header Content-Type: application/xml, IE will throw a Javascript error 'Object Expected' after the line where you try to access an XML element. If you do not set header Cache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging 'challenging'.

Note 3: if the http_request variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition. Declaring the http_request variable local to the function and passing it to the alertContent() function prevents the race condition.

Note 4: To register the call back function onreadystatechange, you cannot have any argument:

http_request.onreadystatechange = function() { alertContents(http_request); };  //1 (simultaneous request)
http_request.onreadystatechange = alertContents(http_request); //2 (does not work)
http_request.onreadystatechange = alertContents;  //3 (global variable)

Method 1 allows to have several requests done in simultaneously, method 2 will not work, method 3 is used if http_request is a global variable

Step 4 – "The X-Files" or Working with the XML Response

In the previous example, after the response to the HTTP request was received, we used the reponseText property of the request object and it contained the contents of the test.html file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:

<?xml version="1.0" ?>
<root>
    I'm a test.
</root>

In the script we only need to change the request line with:

...
onclick="makeRequest('test.xml')">
...

Then in alertContents() we need to replace the alert()-ing line alert(http_request.responseText); with:

var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

This way we took the XMLDocument object given by responseXML and we used DOM methods to access some data contained in the XML document. You can see the test.xml here and the updated test script here.

For more on the DOM methods, be sure to check Mozilla's DOM implementation documents.

{{ wiki.languages( { "ca": "ca/AJAX/Primers_passos", "de": "de/AJAX/Getting_Started", "es": "es/AJAX/Primeros_Pasos", "fr": "fr/AJAX/Premiers_pas", "ja": "ja/AJAX/Getting_Started", "pl": "pl/AJAX/Na_pocz\u0105tek", "pt": "pt/AJAX/Como_come\u00e7ar" } ) }}

리비전 소스

<p><span class="comment">breadcrumbs /breadcrumbs</span>
</p><p>This article guides you through the AJAX basics and gives you two simple hands-on examples to get you started.
</p>
<h3 name="AJAX.EB.9E.80.3F"> AJAX란? </h3>
<p>AJAX (Asynchronous JavaScript and XML)는 수년전부터 두개의 강력한 브라우져에 의해 새로 만들어진 용어입니다. 하지만 최근 Gmail, Google의 추천검색어, 그리고 Google 지도가 나오기전까지 많은 개발자들은 그냥 보고 지나쳤죠.
</p><p>질문할 수 있는 두가지 특징 :
</p>
<ul><li> 웹 페이지를 리로딩(reloading)하지않고 서버에 리퀘스트(request)할수 있음.
</li><li> XML문서로 작업을 하거나 파싱할 수 있음.
</li></ul>
<h3 name="1.EB.8B.A8.EA.B3.84_.E2.80.93_say_.22Please.21.22_or_How_to_Make_an_HTTP_Request"> 1단계 – say "Please!" or How to Make an HTTP Request </h3>
<p>자바스크립트를 사용해서 서버에 HTTP request를 하기위해서, 이런기능을 제공하는 클레스 인스턴스가 필요합니다. 그런 클레스는 인터넷익스플로러(Internet Explorer)에서 최초로 <code>XMLHTTP</code>라고 불리우는 엑티브엑스(ActiveX)로 도입되었습니다. 모질라(Mozilla), 사파리(Safari)그리고 다른 브라우져에서는 마이크로소프트의 엑티브엑스 오브젝트의 특성과 메소드를 지원하기위해 <code>XMLHttpRequest</code>클레스를 제공합니다.
</p><p>결국, 모든브라우져에서 사용할 수 있는 인스턴스를 만들기 위해서는 아래와 같이 하십시오.
</p>
<pre>if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
</pre>
<p>(기술을 목적으로 하기 때문에 위의 예는 XMLHTTP인트턴스를 만드는데 사용된 코드는 약간 간단화 되어 있습니다. 실제 사용예를 보려면 위 문서의 단계3을 보십시오.)
</p><p>서버에서 응답이 XML mime-type 헤더가 아닐경우 어떤 모질라 브라우져에서는 잘 작동하지 않을 수 있습니다. mimetype을 만족시키기위해, 서버로 부터 받은 헤더가 <code>text/xml</code>이 아닐경우 오버라이드하기 위한 다른 메소드로 해결 할 수 있습니다.
</p>
<pre>http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');
</pre>
<p>요구(request)에 의해서 서버로부터 받은 내용을 어떻게 할것인가를 결정하는것이 다음에 할 일입니다. 이번 단계에서는 자바스크립트로 서버로부터 받은 응답을 처리하는 HTTP request에 대해 말할 필요가 있습니다. 이것은 아래와 같은 당신이 사용하고 싶은 자바스크립트 함수 이름(nameOfTheFunction)을 <code>onreadystatechange</code> 프로퍼티로 설정하면 됩니다. :
</p><p><code>http_request.onreadystatechange = nameOfTheFunction;</code>
</p><p>함수 이름뒤에 괄호와 넘어갈 파라미터가 없습니다.  Also, instead of giving a function name, you can use the Javascript technique of defining functions on the fly and define the actions that will process the response right away, like this:
</p>
<pre>http_request.onreadystatechange = function(){
    // do the thing
};
</pre>
<p>Next, after you've declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the <code>open()</code> and <code>send()</code> methods of the HTTP request class, like this:
</p>
<pre>http_request.open('GET', 'http://www.example.org/some.file', true);
http_request.send(null);
</pre>
<ul><li> The first parameter of the call to <code>open()</code> is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">W3C specs</a> 
</li><li> The second parameter is the URL of the page you're requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a 'permission denied' error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.
</li><li> The third parameter sets whether the request is asynchronous. If <code>TRUE</code>, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.
</li></ul>
<p>The parameter to the <code>send()</code> method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:
</p><p><code>name=value&amp;anothername=othervalue&amp;so=on</code>
</p><p>Note that if you want to POST data, you have to change the MIME type of the request using the following line:
</p>
<pre>http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
</pre>
<p>Otherwise, the server will discard the POSTed data.
</p>
<h3 name="Step_2_.E2.80.93_.22There_you_go.21.22_or_Handling_the_Server_Response"> Step 2 – "There you go!" or Handling the Server Response </h3>
<p>Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response. 
</p><p><code>http_request.onreadystatechange = nameOfTheFunction;</code>
</p><p>Let's see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it's OK for you to continue processing it. 
</p>
<pre>if (http_request.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}
</pre>
<p>The full list of the <code>readyState</code> values is as follows:
</p>
<ul><li> 0 (uninitialized)
</li><li> 1 (loading)
</li><li> 2 (loaded)
</li><li> 3 (interactive)
</li><li> 4 (complete)
</li></ul>
<p>(<a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp">Source</a>)
</p><p>The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">W3C site</a>. For our purposes we are only interested in <code>200 OK</code> response.
</p>
<pre>if (http_request.status == 200) {
    // perfect!
} else {
    // there was a problem with the request,
    // for example the response may be a 404 (Not Found)
    // or 500 (Internal Server Error) response codes
}
</pre>
<p>Now after you've checked the state of the request and the HTTP status code of the response, it's up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:
</p>
<ul><li> <code>http_request.responseText</code> – will return the server response as a string of text
</li><li> <code>http_request.responseXML</code> – will return the response as an <code>XMLDocument</code> object you can traverse using the JavaScript DOM functions
</li></ul>
<h3 name="Step_3_.E2.80.93_.22All_together_now.21.22_-_A_Simple_Example"> Step 3 – "All together now!" - A Simple Example </h3>
<p>Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, <code>test.html</code>, which contains the text "I'm a test." and then we'll <code>alert()</code> the contents of the <code>test.html</code> file.
</p>
<pre>&lt;script type="text/javascript" language="javascript"&gt;

    

    function makeRequest(url) {

        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('GET', url, true);
        http_request.send(null);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                alert(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
&lt;/script&gt;
&lt;span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')"&gt;
        Make a request
&lt;/span&gt;
</pre>
<p><br>
In this example:
</p>
<ul><li> The user clicks the link "Make a request" in the browser;
</li><li> This calls the <code>makeRequest()</code> function with a parameter – the name <code>test.html</code> of an HTML file in the same directory;
</li><li> The request is made and then (<code>onreadystatechange</code>) the execution is passed to <code>alertContents()</code>;
</li><li> <code>alertContents()</code> checks if the response was received and it's an OK and then <code>alert()</code>s the contents of the <code>test.html</code> file.
</li></ul>
<p>You can test the example <a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test.html">here</a> and you can see the test file <a class="external" href="http://www.w3clubs.com/mozdev/test.html">here</a>.
</p><p><b>Note</b>: The line <code>                http_request.overrideMimeType('text/xml');</code> above will cause Javascript Console errors in Firefox 1.5b as documented at https://bugzilla.mozilla.org/show_bug.cgi?id=311724 if the page called by XMLHttpRequest is not valid XML (eg, if it is plain text).
</p><p>If you get Syntax Error or Not Well Formed Error on that browser, and you're not trying to load an XML page from XMLHttpRequest, remove that line from your  code.
</p><p><b>Note 2</b>: if you are sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. If you do not set header <code>Content-Type: application/xml</code>, IE will throw a Javascript error 'Object Expected' after the line where you try to access an XML element. If you do not set header <code>Cache-Control: no-cache</code> the browser will cache the response and never re-submit the request, making debugging 'challenging'.
</p><p><b>Note 3</b>: if the http_request variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition.  Declaring the http_request variable local to the function and passing it to the alertContent() function prevents the race condition.
</p><p><b>Note 4</b>: To register the call back function onreadystatechange, you cannot have any argument:
</p>
<pre>http_request.onreadystatechange = function() { alertContents(http_request); };  //1 (simultaneous request)
http_request.onreadystatechange = alertContents(http_request); //2 (does not work)
http_request.onreadystatechange = alertContents;  //3 (global variable)
</pre>
<p>Method 1 allows to have several requests done in simultaneously, method 2 will not work, method 3 is used if http_request is a global variable
</p>
<h3 name="Step_4_.E2.80.93_.22The_X-Files.22_or_Working_with_the_XML_Response"> Step 4 – "The X-Files" or Working with the XML Response </h3>
<p>In the previous example, after the response to the HTTP request was received, we used the <code>reponseText</code> property of the request object and it contained the contents of the <code>test.html</code> file. Now let's try the <code>responseXML</code> property.
</p><p>First off, let's create a valid XML document that we'll request later on. The document (test.xml) contains the following:
</p>
<pre>&lt;?xml version="1.0" ?&gt;
&lt;root&gt;
    I'm a test.
&lt;/root&gt;
</pre>
<p>In the script we only need to change the request line with:
</p>
<pre>...
onclick="makeRequest('test.xml')"&gt;
...
</pre>
<p>Then in <code>alertContents()</code> we need to replace the <code>alert()</code>-ing line <code>alert(http_request.responseText);</code> with:
</p>
<pre>var xmldoc = http_request.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
</pre>
<p>This way we took the <code>XMLDocument</code> object given by <code>responseXML</code> and we used DOM methods to access some data contained in the XML document. You can see the <code>test.xml</code> <a class="external" href="http://www.w3clubs.com/mozdev/test.xml">here</a> and the updated test script <a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test_xml.html">here</a>.
</p><p>For more on the DOM methods, be sure to check <a class="external" href="http://www.mozilla.org/docs/dom/">Mozilla's DOM implementation</a> documents.
</p>{{ wiki.languages( { "ca": "ca/AJAX/Primers_passos", "de": "de/AJAX/Getting_Started", "es": "es/AJAX/Primeros_Pasos", "fr": "fr/AJAX/Premiers_pas", "ja": "ja/AJAX/Getting_Started", "pl": "pl/AJAX/Na_pocz\u0105tek", "pt": "pt/AJAX/Como_come\u00e7ar" } ) }}
현재 리비전 복원