添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
http://www.w3.org/TR/2009/WD-XMLHttpRequest-20090820/
http://www.w3.org/TR/2008/WD-XMLHttpRequest-20080415/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20071026/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070227/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060927/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
Editor:
Anne van Kesteren ( Opera Software ASA ) < [email protected] > © 2009 W3C ® ( MIT , ERCIM , Keio ), All Rights Reserved. W3C liability , trademark and document use rules apply.

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 19 November 2009 Last Call Working Draft of the XMLHttpRequest specification. Please send comments to [email protected] ( archived ) with [XHR] at the start of the subject line before 16 December 2009.

This document is produced by the Web Applications (WebApps) Working Group, part of the Rich Web Clients Activity in the W3C Interaction Domain . Changes made to this document can be found in the W3C public CVS server .

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy . W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy .

Table of Contents

  • 1 Introduction
  • 2 Conformance Dependencies
  • 2.2 Terminology Extensibility
  • 3 Security Considerations
  • 4 The XMLHttpRequest Interface
  • 4.1 Origin and Base URL
  • 4.2 Task Sources Constructors Event Handler Attributes
  • 4.5 States
  • 4.6 Request
  • 4.6.1 The open() method
  • 4.6.2 The setRequestHeader() method
  • 4.6.3 The send() method
  • 4.6.4 Infrastructure for the send() method
  • 4.6.5 The abort() method
  • 4.7 Response
  • 4.7.1 The status attribute
  • 4.7.2 The statusText attribute
  • 4.7.3 The getResponseHeader() method
  • 4.7.4 The getAllResponseHeaders() method
  • 4.7.5 Response Entity Body
  • 4.7.6 The responseText attribute
  • 4.7.7 The responseXML attribute
  • 5 Exceptions
  • Not in this Specification
  • References
  • Acknowledgments

    1 Introduction

    This section is non-normative.

    The XMLHttpRequest object implements an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server. It is the ECMAScript HTTP API.

    The name of the object is XMLHttpRequest for compatibility with the Web, though each component of this name is potentially misleading. First, the object supports any text based format, including XML. Second, it can be used to make requests over both HTTP and HTTPS (some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification). Finally, it supports "requests" in a broad sense of the term as it pertains to HTTP; namely all activity involved with HTTP requests or responses for the defined HTTP methods.

    Some simple code to do something with data from an XML document fetched over the network:

    function test(data) {
     // taking care of data
    function handler() {
     if(this.readyState == 4 && this.status == 200) {
      // so far so good
      if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
         // success!
       test(this.responseXML.getElementById('test').firstChild.data);
       test(null);
     } else if (this.readyState == 4 && this.status != 200) {
      // fetched the wrong page or network error...
      test(null);
    var client = new XMLHttpRequest();
    client.onreadystatechange = handler;
    client.open("GET", "test.xml");
    client.send();

    If you just want to log a message to the server:

    function log(message) {
     var client = new XMLHttpRequest();
     client.open("POST", "/log");
     client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
     client.send(message);
       

    Or if you want to check the status of a document on the server:

    function fetchStatus(address) {
     var client = new XMLHttpRequest();
     client.onreadystatechange = function() {
      // in case of network errors this might not give reliable results
      if(this.readyState == 4)
       returnStatus(this.status);
     client.open("HEAD", address);
     client.send();
      

    2 Conformance

    Everything in this specification is normative except for diagrams, examples, notes and sections marked non-normative.

    The key words must, must not, should and may in this document are to be interpreted as described in RFC 2119. [RFC2119]

    This specification defines the following classes of products:

    Conforming user agent

    A user agent must behave as described in this specification in order to be considered conformant.

    If the user agent is not a conforming XML user agent the XML response entity body must (always) be null.

    User agents may implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

    This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.

  • Conforming XML user agent

    An XML user agent must be a conforming user agent and must be a conforming XML processor that reports violations of namespace well-formedness. [ XML ]

    2.1 Dependencies

    This specification relies on several underlying specifications.

    A conforming user agent must support at least the subset of the functionality defined in DOM Events and DOM Core that this specification relies upon, such as various exceptions and EventTarget . [ DOM2Events ] [ DOM3Core ]

    HTML 5

    A conforming user agent must support at least the subset of the functionality defined in HTML 5 that this specification relies upon, such as the basics of the Window object and serializing a Document object. [ HTML5 ]

    The Window Object 1.0 draft is not referenced normatively as it appears to be no longer maintained and HTML 5 defines the Window object in more detail. This specification already depends on HTML 5 for other reasons so there is not much additional overhead because of this.

    A conforming user agent must support some version of the HTTP protocol. It should support any HTTP method that matches the Method token production and must at least support the following methods:

  • DELETE
  • OPTIONS

    Other requirements regarding HTTP are made throughout the specification. [ RFC2616 ]

    Web IDL
    A conforming user agent must also be a conforming implementation of the IDL fragment in this specification, as described in the Web IDL specification. [ WebIDL ]

    2.2 Terminology

    Comparing two strings in a case-sensitive manner means comparing them exactly, codepoint for codepoint.

    Comparing two strings in an ASCII case-insensitive manner means comparing them exactly, codepoint for codepoint, except that the characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are considered to also match.

    Converting a string to ASCII uppercase means replacing all characters in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) with the corresponding characters in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).

    convert a DOMString to a sequence of Unicode characters is defined by the Web IDL specification. [ WebIDL ]

    The terms and algorithms <fragment> , <scheme> , document base URL , document's character encoding , event handler attributes , event handler event type , fully active , Function , innerHTML , origin , preferred MIME name , resolve a URL , same origin , storage mutex , task , task source , URL , URL character encoding , queue a task , and valid MIME type are defined by the HTML 5 specification. [ HTML5 ]

    The term entity body is used as described in RFC 2616. Method token is used as described in section 5.1.1 of RFC 2616. field-name and field-value are used as described in section 4.2 of RFC 2616. [ RFC2616 ]

    userinfo is used as described in section 3.2.1 of RFC 3986. [ RFC3986 ]

    To dispatch a readystatechange event means that an event with the name readystatechange , which does not bubble and is not cancelable, and which uses the Event interface, is to be dispatched at the XMLHttpRequest object.

    2.3 Extensibility

    Extensions of the API defined by this specification are strongly discouraged . User agents, Working Groups and other interested parties should discuss extensions on a relevant public forum, preferably [email protected] .

    3 Security Considerations

    Security related requirements are made throughout this specification.

    4 The XMLHttpRequest Interface

    The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP.

    [NoInterfaceObject]
    interface XMLHttpRequestEventTarget : EventTarget {
      // for future use
    [Constructor]
    interface XMLHttpRequest : XMLHttpRequestEventTarget {
      // event handler attributes
               attribute Function onreadystatechange;
      // states
      const unsigned short UNSENT = 0;
      const unsigned short OPENED = 1;
      const unsigned short HEADERS_RECEIVED = 2;
      const unsigned short LOADING = 3;
      const unsigned short DONE = 4;
      readonly attribute unsigned short readyState;
      // request
      void open(DOMString method, DOMString url);
      void open(DOMString method, DOMString url, boolean async);
      void open(DOMString method, DOMString url, boolean async, DOMString? user);
      void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);
      void setRequestHeader(DOMString header, DOMString value);
      void send();
      void send(Document data);
      void send([AllowAny] DOMString? data);
      void abort();
      // response
      readonly attribute unsigned short status;
      readonly attribute DOMString statusText;
      DOMString getResponseHeader(DOMString header);
      DOMString getAllResponseHeaders();
      readonly attribute DOMString responseText;
      readonly attribute Document responseXML;
      

    4.1 Origin and Base URL

    Each XMLHttpRequest object has an associated XMLHttpRequest origin and an XMLHttpRequest base URL.

    This specification defines their values when the global object is represented by the Window object. When the XMLHttpRequest object used in other contexts their values will have to be defined as appropriate for that context. That is considered to be out of scope for this specification.

    In environments where the global object is represented by the Window object the XMLHttpRequest object has an associated XMLHttpRequest Document which is the Document object associated with the Window object for which the XMLHttpRequest interface object was created.

    The XMLHttpRequest Document is used to determine the XMLHttpRequest origin and XMLHttpRequest base URL at a later stage.

    4.2 Task Sources

    The following task sources are used by this specification:

    The XMLHttpRequest event task source
    This task source is used for events that are to be asynchronously dispatched.
    The XMLHttpRequest networking task source
    This task source is used for network activity.

    Unless otherwise stated the task source used for all tasks queued in this specification is the XMLHttpRequest event task source.

    4.3 Constructors

    When the XMLHttpRequest() constructor is invoked, the user agent must return a new XMLHttpRequest object.

    4.4 Event Handler Attributes

    The following is the event handler attribute (and its corresponding event handler event type) that must be supported as DOM attribute by the XMLHttpRequest object:

    The XMLHttpRequest object can be in several states. The readyState attribute, on getting, must return the current state, which must be one of the following values:

    UNSENT (numeric value 0)

    The object has been constructed.

    OPENED (numeric value 1)

    The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

    HEADERS_RECEIVED (numeric value 2)

    All HTTP headers have been received. Several response members of the object are now available.

    LOADING (numeric value 3)

    The response entity body is being received.

    DONE (numeric value 4)

    The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

    The OPENED state has an associated send() flag that indicates whether the send() method has been invoked. It can be either true or false and has an initial value of false.

    The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.

    4.6 Request

    The XMLHttpRequest object holds the following request metadata variables:

    The asynchronous flag
    A flag that is either true or false that indicates whether the request is done asynchronously.
    The request method
    The method used in the request.
    The request URL
    The URL used in the request.
    The request username
    The username used in the request or null if there is no username.
    The request password
    The password used in the request or null if there is no password.
    The author request headers
    A list consisting of HTTP header name/value pairs to be used in the request.
    The request entity body
    The entity body used in the request.

    4.6.1 The open() method

    When the open( method , url , async , user , password ) method is invoked, the user agent must run these steps (unless otherwise indicated):

    If the XMLHttpRequest object has an associated XMLHttpRequest Document run these substeps:

    If the XMLHttpRequest Document is not fully active raise an INVALID_STATE_ERR exception and terminate the overall set of steps.

    Let XMLHttpRequest base URL be the document base URL of the XMLHttpRequest Document .

    Let XMLHttpRequest origin be the origin of the XMLHttpRequest Document .

    If method does not match the Method token production raise a SYNTAX_ERR exception and terminate these steps.

    If method is an ASCII case-insensitive match for CONNECT , DELETE , GET , HEAD , OPTIONS , POST , PUT , TRACE , or TRACK convert method to ASCII uppercase .

    If it does not match any of the above, it is passed through literally , including in the final request.

    If method is a case-sensitive match for CONNECT , TRACE , or TRACK the user agent should raise a SECURITY_ERR exception and terminate these steps.

    Allowing these methods poses a security risk. [ HTTPVERBSEC ]

    Let url be a URL .

    Let URL character encoding of url be UTF-8.

    Resolve url relative to the XMLHttpRequest base URL . If the algorithm returns an error raise a SYNTAX_ERR exception and terminate these steps.

    If url contains an unsupported <scheme> raise a NOT_SUPPORTED_ERR and terminate these steps.

    If the "user:password" format in the userinfo production is not supported for the relevant scheme and url contains this format raise a SYNTAX_ERR and terminate these steps.

    If url contains the "user:password" format let temp user be the user part and temp password be the password part.

    If url just contains the "user" format let temp user be the user part.

    If the origin of url is not same origin with the XMLHttpRequest origin the user agent should raise a SECURITY_ERR exception and terminate these steps.

    Let async be the value of the async argument or true if it was omitted.

    If the user argument was not omitted follow these sub steps:

    If the syntax of user does not match the syntax specified by the relevant authentication scheme, raise a SYNTAX_ERR exception and terminate the overall set of steps.

    If user is null let temp user be null.

    Otherwise let temp user be user .

    These steps override anything that may have been set by the url argument.

    If the password argument was not omitted follow these sub steps:

    If the syntax of password does not match the syntax specified by the relevant authentication scheme, raise a SYNTAX_ERR exception and terminate the overall set of steps.

    If password is null let temp password be null.

    Otherwise let temp password be password .

    These steps override anything that may have been set by the url argument.

    Abort the send() algorithm .

    The user agent should cancel any network activity for which the object is responsible.

    A future version or extension of this specification will define a way of doing cross-origin requests.

    4.6.2 The setRequestHeader() method

    As indicated in the algorithm below certain headers cannot be set and are left up to the user agent. In addition there are certain other headers the user agent will take control of if they are not set by the author as indicated at the end of the send() method section.

    The setRequestHeader() method appends a value if the HTTP header given as argument is already part of the author request headers list.

    When the setRequestHeader( header , value ) method is invoked, the user agent must run these steps (unless otherwise indicated):

    If the state is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

    If the send() flag is true raise an INVALID_STATE_ERR exception and terminate these steps.

    If header does not match the field-name production raise a SYNTAX_ERR exception and terminate these steps.

    If the value argument does not match the field-value production raise a SYNTAX_ERR and terminate these steps.

    The empty string is legal and represents the empty header value.

    For security reasons, these steps should be terminated if header is an ASCII case-insensitive match for one of the following headers:

  • Accept-Charset
  • Accept-Encoding
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Content-Transfer-Encoding
  • Expect
  • Keep-Alive
  • Referer
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent

    … or if the start of header is an ASCII case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec- ).

    The above headers are not allowed to be set as they are better controlled by the user agent as it knows best what value they should have. Header names starting with Sec- are not allowed to be set to allow new headers to be minted in the future that are guaranteed not to come from XMLHttpRequest . (Older clients would however still be vulnerable as they allow such headers to be set.)

    If header is not in the author request headers list append header with its associated value to the list and terminate these steps.

    If header is in the author request headers list either use multiple headers, combine the values or use a combination of those (section 4.2, RFC 2616). [ RFC2616 ]

    See also the send() method regarding user agent header handling for caching, authentication, proxies, and cookies.

    // The following script:
    var client = new XMLHttpRequest();
    client.open('GET', 'demo.cgi');
    client.setRequestHeader('X-Test', 'one');
    client.setRequestHeader('X-Test', 'two');
    client.send();
    // ...would result in the following header being sent:
    X-Test: one, two
      

    4.6.3 The send() method

    When the send(data) method is invoked, the user agent must run the following steps (unless otherwise noted). This algorithm gets aborted when the open() or abort() method is invoked. When the send() algorithm is aborted the user agent must terminate the algorithm after finishing the step it is on.

    The send() algorithm can only be aborted when the asynchronous flag is true and only after the method call has returned.

    If the state is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

    If the send() flag is true raise an INVALID_STATE_ERR exception and terminate these steps.

    If the request method is GET or HEAD act as if data is null.

    If the data argument has been omitted or is null, do not include a request entity body and go to the next step.

    Otherwise, let encoding be UTF-8, mime be text/plain, and then follow these rules:

    data is a Document

    Let encoding be the preferred MIME name of the character encoding of data. If encoding is UTF-16 change it to UTF-8.

    Let mime be application/xml.

    Let the request entity body be the result of getting the innerHTML attribute on data converted to Unicode and encoded as encoding. Re-raise any exception this raises.

    In particular, if the document cannot be serialized an INVALID_STATE_ERR exception is raised.

    Subsequent changes to the Document have no effect on what is submitted.

  • data is a DOMString

    Let the request entity body be data converted to Unicode and encoded as UTF-8.

    If a Content-Type header is set using setRequestHeader() and its value is a valid MIME type and it has a charset parameter whose value is not an ASCII case-insensitive match for encoding , set all the charset parameters to encoding .

    If no Content-Type header has been set using setRequestHeader() set a Content-Type request header with a value of mime ;charset= encoding .

    Make a request to request URL , using HTTP method request method , user request username (if non-null) and password request password (if non-null), taking into account the request entity body , list of author request headers and the rules listed at the end of this section.

    If there are cookies to be set, run the cookie steps .

    If the asynchronous flag is false

    While making the request also follow the same-origin request event rules .

    The send() method call will now be returned by virtue of this algorithm ending.

    If the asynchronous flag is true

    While processing the request, as data becomes available and when the end user interferes with the request, queue tasks to follow the same-origin request event rules using the XMLHttpRequest networking task source as task source .

    If the user agent allows the end user to configure a proxy it should modify the request appropriately; i.e. connect to the proxy host instead of the origin server, modify the Request-Line and send Proxy-Authorization headers as specified.

    If the user agent supports HTTP Authentication and Authorization is not in the list of author request headers , it should consider requests originating from the XMLHttpRequest object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorized requests appropriately. If authentication fails, and request username and request password are both null, user agents should prompt the end user for credentials. If authentication fails, and request username and request password are provided, user agents must not prompt the end user for credentials. [ RFC2617 ]

    End users are not prompted if credentials are provided through the open() API so that authors can implement their own user interface.

    If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie and Set-Cookie2 response headers, and sent in the Cookie header) as applicable. [ COOKIES ]

    If the user agent implements a HTTP cache it should respect Cache-Control request headers set by setRequestHeader() (e.g., Cache-Control: no-cache bypasses the cache). It must not send Cache-Control or Pragma request headers automatically unless the end user explicitly requests such behavior (e.g. by (force-)reloading the page).

    For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow setRequestHeader() to override automatic cache validation by setting request headers (e.g., If-None-Match , If-Modified-Since ), in which case 304 Not Modified responses must be passed through. [ RFC2616 ]

    If the user agent implements server-driven content-negotiation it should set Accept-Encoding and Accept-Charset headers as appropriate. For Accept and Accept-Language the user agent must follow these constraints:

    Both headers must not be modified if they are already set through setRequestHeader() .

    If not set through setRequestHeader() Accept-Language should set as appropriate.

    If not set through setRequestHeader() Accept must be set with as value */* .

    Responses must have the content-encodings automatically decoded. [ RFC2616 ]

    Besides the author request headers user agents should not include additional request headers other than those mentioned above or other than those authors are not allowed to set using setRequestHeader() . This ensures that authors have a reasonably predictable API.

    4.6.4 Infrastructure for the send() method

    The cookie steps are as follows:

    Wait until ownership of the storage mutex can be taken.

    Take ownership of the storage mutex .

    Update the cookies. [ COOKIES ]

    Release the storage mutex so that it is once again free.

    If the redirect does not violate security (it is same origin for instance), infinite loop precautions, and the scheme is supported, transparently follow the redirect while observing the same-origin request event rules .

    HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.

    Otherwise, this is a network error .

    If the end user cancels the download

    This is an abort error .

    In case of network errors

    In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error . Do not request any kind of end user interaction.

    This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.

    Once all HTTP headers have been received and the asynchronous flag is true

    Switch to the HEADERS_RECEIVED state .

    Once the first byte (or more) of the response entity body has been received and the asynchronous flag is true
    If there is no response entity body and the asynchronous flag is

    Switch to the LOADING state .

    Once the whole response entity body has been received
    If there is no response entity body and the asynchronous flag is false or the state is LOADING

    Switch to the DONE state .

    When something is said to be a network error run the request error steps for exception NETWORK_ERR .

    When something is said to be an abort error run the request error steps for exception ABORT_ERR .

    When something is said to be a request error for exception exception run these steps:

    Set the response entity body to null.

    Set the the error flag to true.

    Empty the list of author request headers .

    Switch the state to DONE .

    If the asynchronous flag is false raise an exception exception and terminate the overall set of steps.

    If the asynchronous flag is true queue a task to dispatch a readystatechange event .

    Terminate the overall set of steps.

    It is likely that a future version of this specification will dispatch an error / abort event here as well. (Depending on the type of error.)

    When it is said to switch to the HEADERS_RECEIVED state run these steps:

    Switch the state to HEADERS_RECEIVED .

    Queue a task to dispatch a readystatechange event .

    If the state is UNSENT , OPENED with the send() flag being false, or DONE go to the next step.

    Otherwise run these substeps:

    Switch the state to DONE .

    Set the send() flag to false.

    Dispatch a readystatechange event .

    It is likely that a future version of this specification will dispatch an abort event here.

    Switch the state to UNSENT .

    No readystatechange event is dispatched.

    4.7 Response

    4.7.1 The status attribute

    The status attribute must return the result of running these steps:

    If the state is UNSENT or OPENED return 0 and terminate these steps.

    If the error flag is true return 0 and terminate these steps.

    Return the HTTP status code.

    4.7.2 The statusText attribute

    The statusText attribute must return the result of running these steps:

    If the state is UNSENT or OPENED return the empty string and terminate these steps.

    If the error flag is true return the empty string and terminate these steps.

    Return the HTTP status text.

    4.7.3 The getResponseHeader() method

    When the getResponseHeader( header ) is invoked, the user agent must run these steps:

    If the state is UNSENT or OPENED return null and terminate these steps.

    If the error flag is true return null and terminate these steps.

    If header is an ASCII case-insensitive match for Set-Cookie or Set-Cookie2 return null and terminate these steps.

    If header is an ASCII case-insensitive match for multiple HTTP response headers, return the values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair and terminate these steps.

    If header is an ASCII case-insensitive match for a single HTTP response header, return the value of that header and terminate these steps.

    Return null.

    // The following script:
    var client = new XMLHttpRequest();
    client.open("GET", "test.txt", true);
    client.send();
    client.onreadystatechange = function() {
     if(this.readyState == 2) {
      print(client.getResponseHeader("Content-Type"));
    // ...should output something similar to the following text:
    Content-Type: text/plain; charset=utf-8

    4.7.4 The getAllResponseHeaders() method

    When the getAllResponseHeaders() method is invoked, the user agent must run the following steps:

    If the state is UNSENT or OPENED return the empty string and terminate these steps.

    If the error flag is true return the empty string and terminate these steps.

    Return all the HTTP headers, excluding headers that are an ASCII case-insensitive match for Set-Cookie or Set-Cookie2 , as a single string, with each header line separated by a U+000D CR U+000A LF pair excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

    // The following script:
    var client = new XMLHttpRequest();
    client.open("GET", "test.txt", true);
    client.send();
    client.onreadystatechange = function() {
     if(this.readyState == 2) {
      print(this.getAllResponseHeaders());
    // ...should output something similar to the following text:
    Date: Sun, 24 Oct 2004 04:58:38 GMT
    Server: Apache/1.3.31 (Unix)
    Keep-Alive: timeout=15, max=99
    Connection: Keep-Alive
    Transfer-Encoding: chunked
    Content-Type: text/plain; charset=utf-8

    4.7.5 Response Entity

    The response entity body is the fragment of the entity body received so far ( LOADING state) or the complete entity body ( DONE state). If there is no entity body the response entity body is null.

    The text response entity body is a DOMString representing the response entity body . The text response entity body is the return value of the following algorithm:

    If the response entity body is null return the empty string and terminate these steps.

    Let charset be null.

    If there is no Content-Type header or there is a Content-Type header which contains a MIME type that is text/xml , application/xml or ends in +xml (ignoring any parameters) use the rules set forth in the XML specifications to determine the character encoding. Let charset be the determined character encoding. [ XML ]

    If the Content-Type header contains a text/html MIME type follow the rules set forth in the HTML 5 specification to determine the character encoding. Let charset be the determined character encoding. [ HTML5 ]

    If the MIME type specified by the Content-Type header contains a charset parameter and charset is null let charset be the value of that parameter.

    The algorithms described by the XML and HTML specifications already take Content-Type into account.

    If charset is null then, for each of the rows in the following table, starting with the first one and going down, if the first bytes of bytes match the bytes given in the first column, then let charset be the encoding given in the cell in the second column of that row. If there is no match charset remains null.

    Return the result of decoding the response entity body using charset . Replace bytes or sequences of bytes that are not valid according to the charset with a single U+FFFD REPLACEMENT CHARACTER character.

    Authors are strongly encouraged to encode their resources using UTF-8.

    The XML response entity body is either a Document representing the response entity body or null. The XML response entity body is the return value of the following algorithm:

    If the response entity body is null terminate these steps and return null.

    If a Content-Type is present and it does not contain a MIME type (ignoring any parameters) that is text/xml , application/xml or ends in +xml terminate these steps and return null. (Do not terminate these steps if there is no Content-Type header at all.)

    Parse the response entity body into a document tree following the rules from the XML specifications. Let the result be parsed document . If this fails (unsupported character encoding, namespace well-formedness error, et cetera) terminate these steps return null. [ XML ]

    Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.

    Return an object implementing the Document interface representing the parsed document .

    4.7.6 The responseText attribute

    The responseText attribute must return the result of running these steps:

    If the state is not LOADING or DONE return the empty string and terminate these steps.

    Return the text response entity body .

    4.7.7 The responseXML attribute

    The responseXML attribute must return the result of running these steps:

    If the state is not DONE return null and terminate these steps.

    Return the XML response entity body .

    5 Exceptions

    Several algorithms in this specification may result in an exception being thrown. These exceptions are all part of the group ExceptionCode and use the DOMException object, which is defined in DOM Level 3 Core. In addition this specification extends the ExceptionCode group with several new constants as indicated below. [ DOM3Core ]

    Thus, exceptions used by this specification and not defined in this section are defined by DOM Level 3 Core.

    const unsigned short SECURITY_ERR = 18;
    const unsigned short NETWORK_ERR = 19;
    const unsigned short ABORT_ERR = 20;

    The SECURITY_ERR exception is raised if an attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.

    The NETWORK_ERR exception is raised when a network error occurs in synchronous requests.

    The ABORT_ERR exception is raised when the user aborts a request in synchronous requests.

    These exceptions will be folded into an update of DOM Level 3 Core in due course, as they are appropriate for other API specifications as well.

    Not in this Specification

    This section is non-normative.

    This specification does not include the following features which are being considered for a future version of this specification:

  • load event and onload attribute;
  • error event and onerror attribute;
  • progress event and onprogress attribute;
  • abort event and onabort attribute;
  • Timers have been suggested, perhaps an ontimeout attribute;
  • Property to disable following redirects;
  • responseXML for text/html documents;
  • Cross-origin XMLHttpRequest ;
  • responseBody to deal with byte streams;
  • overrideMimeType to fix up MIME types;
  • getRequestHeader() and removeRequestHeader() .

    References

    Unless marked "Non-normative" these references are normative.

    [ COOKIES ]
    HTTP State Management Mechanism , D. Kristol, L. Montulli, editors. IETF, February 1997.
    HTTP State Management Mechanism , D. Kristol, L. Montulli, editors. IETF, October 2000.
    [ DOM2Events ]
    Document Object Model (DOM) Level 2 Events Specification , T. Pixley, editor. W3C, November 2000.
    [ DOM3Core ]
    Document Object Model (DOM) Level 3 Core Specification , A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne, editors. W3C, April 2004.
    [ ECMAScript ]
    ECMAScript Language Specification , Third Edition. ECMA, December 1999.
    [ HTML5 ]
    HTML 5 (work in progress), I. Hickson, D. Hyatt, editors. W3C, 2008.
    HTML 5 (work in progress), I. Hickson, editor. WHATWG, 2008.
    [ HTTPVERBSEC ]
    (Non-normative) Multiple vendors' web servers enable HTTP TRACE method by default , US-CERT.
    (Non-normative) Microsoft Internet Information Server (IIS) vulnerable to cross-site scripting via HTTP TRACK method , US-CERT.
    (Non-normative) HTTP proxy default configurations allow arbitrary TCP connections , US-CERT.
    [ RFC2119 ]
    Key words for use in RFCs to Indicate Requirement Levels , S. Bradner. IETF, March 1997.
    [ RFC2616 ]
    Hypertext Transfer Protocol -- HTTP/1.1 , R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee, editors. IETF, June 1999.
    [ RFC2617 ]
    HTTP Authentication: Basic and Digest Access Authentication , P. Hallam-Baker, J. Hostetler, S. Lawrence, P. Leach, A. Luotonen, L. Stewart, editors. IETF, June 1999.
    [ RFC3986 ]
    Uniform Resource Identifier (URI): Generic Syntax , T. Berners-Lee, R. Fielding, L. Masinter, editors. IETF, January 2005.
    [ WebIDL ] IDL (work in progress), C. McCormack, editor. W3C, 2009.
    [ XML ]
    Extensible Markup Language (XML) 1.0 (Fifth Edition) , T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau, editors. W3C, November 2008.
    Namespaces in XML (Second Edition) , T. Bray, D. Hollander, A. Layman, R. Tobin, editors. W3C, August 2006.

    Acknowledgments

    The editor would like to thank Addison Phillips, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Håsäther, Dean Jackson, Denis Sureau, Doug Schepers, Douglas Livingstone, Elliotte Harold, Eric Lawrence, Erik Dahlström, Sam Sneddon, Gideon Cohn, Gorm Haug Eriksen, Hallvord R. M. Steen, Håkon Wium Lie, Ian Davis, Ian Hickson, Ivan Herman, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mohamed Zergaoui, Pawel Glowacki, Peter Michaux, Robin Berjon, Ruud Steltenpool, Simon Pieters, Stewart Brodie, Sunava Dutta, Thomas Roessler, Tom Magliery, and Zhenbin Xu for their contributions to this specification.

    Special thanks to the Microsoft employees who first implemented the XMLHttpRequest interface, which was first widely deployed by the Windows Internet Explorer browser.

    Special thanks also to the WHATWG for drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to

  •