mozilla

Revision 48723 of Getting Started

  • Revision slug: AJAX/Getting_Started
  • Revision title: Getting Started
  • Revision id: 48723
  • Created:
  • Creator: R01cn
  • Is current revision? No
  • Comment /* Step 2 – "There you go!" or Handling the Server Response */

Revision Content

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

What's AJAX?

AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google suggest, and Google Maps hit the streets.

The two features in question are that you can:

  • Make requests to the server without reloading the page
  • Parse and work with XML documents

Step 1 – say "Please!" or How to Make an HTTP Request
第1步 - 显示“你好�?�?,�?�如何形�?一个HTTP请求

In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides you this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called XMLHTTP. Then Mozilla, Safari and other browsers followed, implementing an XMLHttpRequest class that supports the methods and properties of Microsoft's original ActiveX object.
为了形�?一个�?�使用JavaSctipt的�?务器�?��?的HTTP请求,你需�?一个类的实例,由它�?�为你�??供这个功能。这个类最�?是作为ActiveX对象在IE中引入的,称为XMLHTTP。�?��?�,Mozilla�?Safari和其它�?览器也相继引入,这些�?览器实现了一个XMLHttpReqrest类,由它�?�支�?微软的ActiveX对象的属性和方法。

As a result, in order to create a cross-browser instance (object) of the required class, you can do:
于是,为了生�?适应�?��?�?览器的这个必�?类的实例,你�?�以这样�?�:

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

(For illustration purposes, the above is a bit simplified version of the code to be used for creating an XMLHTTP instance. For a more real-life example, see step 3 of this article.)
(出于例�?的目的,上�?�的代�?用�?�生�?XMLHTTP实例有点简化了。更实用的代�?示例�?本文章的第3步)

Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML mime-type header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not text/xml.
如果从�?务器返回的�?应的XML文件�?是mime型文件头,有些Mozilla版本的�?览器则�?能很好地工作。为了满足这个�?�件,你�?�以调用一个附加的方法�?�覆盖由�?务器�?��?�的文件头,以防这个文件�?是text/xml格�?。

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

The next thing is to decide what you want to do after you receive the server response to your request. At this stage you just need to tell the HTTP request object which JavaScript function will do the work of processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function you plan to use, like this:
下一步�?�?�的事情是,在你接�?�到�?务器对你的请求作出的�?应之�?�,你想�?�什么?在这一步中,你�?�需�?告诉这个HTTP请求对象,用哪一个Java脚本函数�?�处�?�这个请求。这�?��?将这个对象的onreadystatechange属性设置给你打算使用的那个Java脚本函数,�?��?�完�?。例如这样:

http_request.onreadystatechange = nameOfTheFunction;

Note that there are no brackets after the function name and no parameters passed. 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:
注�?,在函数�??的�?��?�没有括�?�,也未传递�?�数。此外,�?给出函数�??,你也�?�以使用未工作的定义函数所带有的Java脚本技术,并自定义正确地处�?�该�?应的过程行为,象这样:

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请求类的open()send()方法,象这样:

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.
  • 调用open()的第一个�?�数是你想使用的HTTP请求的方法——GET�?POST�?HEAD,或其它方法,这些方法是你的�?务器所支�?的。这些方法�?象�?一�?HTTP标准一样,用大写字�?。�?�则有些�?览器(如Firefox)�?�能�?会处�?�这个请求。更多的�?�以使用的HTTP请求方法的信�?�,�?�以�?�考W3C specs
  • 第二个�?�数是你�?请求的页�?�的URL地�?�。出于安全性,你�?能调用第三方域内的页�?�。请对你的所有页�?�,确�?使用确切的域�??。�?�则,当你调用open()时,你会得到一个'permission denied'(拒�?访问)错误信�?�。一个常�?的缺陷是,用domain.tld�?�访问你的网站,但你希望访问的�?�是www.domain.tld中的页�?�。
  • 第三个�?�数设置这个请求是�?��?�?�步。如果用TRUE,那末当�?务器的请求还没有到达的时候,这个Java脚本函数就会执行。这是AJAX中的A情况。

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:
传递给send()方法的�?�数,�?�以是你在POST这个请求的时候,任何你希望�?��?给�?务器的数�?�。这些数�?�应该采用查询字符串的格�?,象这样:

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:
注�?,如果你想POST数�?�,你必须用下�?�这一行代�?�?�改�?�这个请求的MIME类型:

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

Otherwise, the server will discard the POSTed data.
�?�则,�?务器会丢弃这个POST的数�?�。

Step 2 – "There you go!" or Handling the Server Response
第2步 — “你�?去的地方�?,�?�,处�?��?务器的�?应

Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.
请记�?,当你�?��?这个请求的时候,你所�??供的Java脚本函数的�??字(由这个函数处�?��?应)。

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.
让我们看看这个函数应用�?�什么。首先,它需�?检查请求的状�?。如果这个状�?的值是4,这�?味�?�已�?接�?�到了�?务器的全部�?应,并且已�?�?�好了继续处�?�这个�?应的准备。

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:
readyState的值所代表的�?�义如下:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)
  • 0 (未�?始化的)
  • 1 (正在装载)
  • 2 (已�?装载)
  • 3 (正在交互)
  • 4 (已完�?)

(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.
下一步�?检查的工作是HTTP�?务�?应的状�?�?。全部�?�能的状�?�?列在W3C site中。我们感兴趣的�?�是状�?�?为200 OK的�?应。

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状�?�?之�?�,已�?到了你想对已�?从�?务器�?��?�的这些数�?�的时候了。你有两个选择�?�处�?�这些数�?�:

  • 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
  • http_request.responseText — 作为文本字符串返回过�?�的�?务器�?应
  • http_request.responseXML — 作为XMLDocument(XML文档)对象返回过�?�的数�?�(这�?情况下,你�?�以�?使用Java脚本的DOM函数)。

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" } ) }}

Revision Source

<p>
</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="What.27s_AJAX.3F"> What's AJAX? </h3>
<p>AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google suggest, and Google Maps hit the streets.
</p><p>The two features in question are that you can:
</p>
<ul><li> Make requests to the server without reloading the page
</li><li> Parse and work with XML documents
</li></ul>
<h3 name="Step_1_.E2.80.93_say_.22Please.21.22_or_How_to_Make_an_HTTP_Request.E7.AC.AC1.E6.AD.A5_-_.E6.98.BE.E7.A4.BA.E2.80.9C.E4.BD.A0.E5.A5.BD.EF.BF.BD.3F.EF.BF.BD.3F.EF.BC.8C.EF.BF.BD.3F.EF.BF.BD.E5.A6.82.E4.BD.95.E5.BD.A2.EF.BF.BD.3F.E4.B8.80.E4.B8.AAHTTP.E8.AF.B7.E6.B1.82"> Step 1 – say "Please!" or How to Make an HTTP Request<br>第1步 - 显示“你好�?�?,�?�如何形�?一个HTTP请求 </h3>
<p>In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides you this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called <code>XMLHTTP</code>. Then Mozilla, Safari and other browsers followed, implementing an <code>XMLHttpRequest</code> class that supports the methods and properties of Microsoft's original ActiveX object.<br>
为了形�?一个�?�使用JavaSctipt的�?务器�?��?的HTTP请求,你需�?一个类的实例,由它�?�为你�??供这个功能。这个类最�?是作为ActiveX对象在IE中引入的,称为<code>XMLHTTP</code>。�?��?�,Mozilla�?Safari和其它�?览器也相继引入,这些�?览器实现了一个<code>XMLHttpReqrest</code>类,由它�?�支�?微软的ActiveX对象的属性和方法。
</p><p>As a result, in order to create a cross-browser instance (object) of the required class, you can do:<br>
于是,为了生�?适应�?��?�?览器的这个必�?类的实例,你�?�以这样�?�:
</p>
<pre>if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
</pre>
<p>(For illustration purposes, the above is a bit simplified version of the code to be used for creating an XMLHTTP instance. For a more real-life example, see step 3 of this article.)<br>
(出于例�?的目的,上�?�的代�?用�?�生�?XMLHTTP实例有点简化了。更实用的代�?示例�?本文章的第3步)
</p><p>Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML mime-type header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not <code>text/xml</code>.<br>
如果从�?务器返回的�?应的XML文件�?是mime型文件头,有些Mozilla版本的�?览器则�?能很好地工作。为了满足这个�?�件,你�?�以调用一个附加的方法�?�覆盖由�?务器�?��?�的文件头,以防这个文件�?是<code>text/xml</code>格�?。
</p>
<pre>http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');
</pre>
<p>The next thing is to decide what you want to do after you receive the server response to your request. At this stage you just need to tell the HTTP request object which JavaScript function will do the work of processing the response. This is done by setting the <code>onreadystatechange</code> property of the object to the name of the JavaScript function you plan to use, like this:<br>
下一步�?�?�的事情是,在你接�?�到�?务器对你的请求作出的�?应之�?�,你想�?�什么?在这一步中,你�?�需�?告诉这个HTTP请求对象,用哪一个Java脚本函数�?�处�?�这个请求。这�?��?将这个对象的<code>onreadystatechange</code>属性设置给你打算使用的那个Java脚本函数,�?��?�完�?。例如这样:
</p><p><code>http_request.onreadystatechange = nameOfTheFunction;</code>
</p><p>Note that there are no brackets after the function name and no parameters passed. 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:<br>
注�?,在函数�??的�?��?�没有括�?�,也未传递�?�数。此外,�?给出函数�??,你也�?�以使用未工作的定义函数所带有的Java脚本技术,并自定义正确地处�?�该�?应的过程行为,象这样:
</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:<br>
下一步,在你已�?申明了接�?�到�?应立�?�需�?处�?�的事情之�?�,你需�?真正地形�?这个请求。你需�?调用HTTP请求类的<code>open()</code>和<code>send()</code>方法,象这样:
</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><li> 调用<code>open()</code>的第一个�?�数是你想使用的HTTP请求的方法——GET�?POST�?HEAD,或其它方法,这些方法是你的�?务器所支�?的。这些方法�?象�?一�?HTTP标准一样,用大写字�?。�?�则有些�?览器(如Firefox)�?�能�?会处�?�这个请求。更多的�?�以使用的HTTP请求方法的信�?�,�?�以�?�考<a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">W3C specs</a>
</li><li> 第二个�?�数是你�?请求的页�?�的URL地�?�。出于安全性,你�?能调用第三方域内的页�?�。请对你的所有页�?�,确�?使用确切的域�??。�?�则,当你调用open()时,你会得到一个'permission denied'(拒�?访问)错误信�?�。一个常�?的缺陷是,用domain.tld�?�访问你的网站,但你希望访问的�?�是www.domain.tld中的页�?�。
</li><li> 第三个�?�数设置这个请求是�?��?�?�步。如果用<code>TRUE</code>,那末当�?务器的请求还没有到达的时候,这个Java脚本函数就会执行。这是AJAX中的A情况。
</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:<br>
传递给<code>send()</code>方法的�?�数,�?�以是你在POST这个请求的时候,任何你希望�?��?给�?务器的数�?�。这些数�?�应该采用查询字符串的格�?,象这样:
</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:<br>
注�?,如果你想POST数�?�,你必须用下�?�这一行代�?�?�改�?�这个请求的MIME类型:
</p>
<pre>http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
</pre>
<p>Otherwise, the server will discard the POSTed data.<br>
�?�则,�?务器会丢弃这个POST的数�?�。
</p>
<h3 name="Step_2_.E2.80.93_.22There_you_go.21.22_or_Handling_the_Server_Response.E7.AC.AC2.E6.AD.A5_.E2.80.94_.E2.80.9C.E4.BD.A0.EF.BF.BD.3F.E5.8E.BB.E7.9A.84.E5.9C.B0.E6.96.B9.EF.BF.BD.3F.EF.BC.8C.EF.BF.BD.3F.EF.BF.BD.EF.BC.8C.E5.A4.84.EF.BF.BD.3F.EF.BF.BD.EF.BF.BD.3F.E5.8A.A1.E5.99.A8.E7.9A.84.EF.BF.BD.3F.E5.BA.94"> Step 2 – "There you go!" or Handling the Server Response<br>第2步 — “你�?去的地方�?,�?�,处�?��?务器的�?应 </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.<br>
请记�?,当你�?��?这个请求的时候,你所�??供的Java脚本函数的�??字(由这个函数处�?��?应)。
</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.<br>
让我们看看这个函数应用�?�什么。首先,它需�?检查请求的状�?。如果这个状�?的值是4,这�?味�?�已�?接�?�到了�?务器的全部�?应,并且已�?�?�好了继续处�?�这个�?应的准备。
</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:<br>
<code>readyState</code>的值所代表的�?�义如下:
</p>
<ul><li> 0 (uninitialized)
</li><li> 1 (loading)
</li><li> 2 (loaded)
</li><li> 3 (interactive)
</li><li> 4 (complete)
</li><li> 0 (未�?始化的)
</li><li> 1 (正在装载)
</li><li> 2 (已�?装载)
</li><li> 3 (正在交互)
</li><li> 4 (已完�?)
</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.<br>
下一步�?检查的工作是HTTP�?务�?应的状�?�?。全部�?�能的状�?�?列在<a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">W3C site</a>中。我们感兴趣的�?�是状�?�?为<code>200 OK</code>的�?应。
</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:<br>
现在,当你已�?检查了请求的状�?和�?应的HTTP状�?�?之�?�,已�?到了你想对已�?从�?务器�?��?�的这些数�?�的时候了。你有两个选择�?�处�?�这些数�?�:
</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><li> <code>http_request.responseText</code> — 作为文本字符串返回过�?�的�?务器�?应
</li><li> <code>http_request.responseXML</code> — 作为<code>XMLDocument</code>(XML文档)对象返回过�?�的数�?�(这�?情况下,你�?�以�?使用Java脚本的DOM函数)。
</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" } ) }}
Revert to this revision