[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest [Back]  [Original]

XMLHttpRequest - API | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

XMLHttpRequest

Baseline Widely available *

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

* Some parts of this feature may have varying levels of support.

XMLHttpRequest HTTP-.

XMLHttpRequest, .

HTTP- XMLHttpRequest-, URL . , HTTP-.

js
function reqListener() {
  console.log(this.responseText);
}

const req = new XMLHttpRequest();
req.addEventListener("load", reqListener);
req.open("GET", "http://www.example.org/example.txt");
req.send();

In this article

, XMLHttpRequest, . async ( ) XMLHttpRequest.open(). true , , .

, , . , .

: XMLHttpRequest , XML . "XML" , XML.

XMLHttpRequest() . . , .

responseXML

XMLHttpRequest XML-, responseXML DOM-, XML-, . :

  1. XPath ( ) XML-.
  2. XML .
  3. XMLSerializer DOM- .
  4. RegExp, . , RegExp. , , XML- -, , , .

: responseXML HTML. HTML XMLHttpRequest.

HTML responseText

XMLHttpRequest HTML-, responseText "" HTML, . "" HTML:

  1. XMLHttpRequest.responseXML, HTML XMLHttpRequest.
  2. fragment.body.innerHTML DOM-.
  3. RegExp, HTML. , RegExp. , , HTML -, , , .

XMLHttpRequest , . XMLHttpRequest . overrideMimeType().

js
const req = new XMLHttpRequest();
req.open("GET", url);
//         
req.overrideMimeType("text/plain; charset=x-user-defined");
/* ... */

, , responseType , .

, "arraybuffer" responseType ArrayBuffer, .

js
const req = new XMLHttpRequest();

req.onload = (e) => {
  const arraybuffer = req.response; //  response,  responseText
  /* ... */
};
req.open("GET", url);
req.responseType = "arraybuffer";
req.send();

.

XMLHttpRequest , : , .

XMLHttpRequest progress ProgressEvent. :

progress

.

load

, response.

js
const req = new XMLHttpRequest();

req.addEventListener("progress", updateProgress);
req.addEventListener("load", transferComplete);
req.addEventListener("error", transferFailed);
req.addEventListener("abort", transferCanceled);

req.open();

// ...

//        ()
function updateProgress(event) {
  if (event.lengthComputable) {
    const percentComplete = (event.loaded / event.total) * 100;
    // ...
  } else {
    //    ,    
  }
}

function transferComplete(evt) {
  console.log(" .");
}

function transferFailed(evt) {
  console.log("   .");
}

function transferCanceled(evt) {
  console.log("  .");
}

3-6 , XMLHttpRequest.

: open(). progress- .

progress, updateProgress() , , , total loaded. , lengthComputable false.

, . XMLHttpRequest, , XMLHttpRequest.upload:

js
const req = new XMLHttpRequest();

req.upload.addEventListener("progress", updateProgress);
req.upload.addEventListener("load", transferComplete);
req.upload.addEventListener("error", transferFailed);
req.upload.addEventListener("abort", transferCanceled);

req.open();

: file:.

, , , , progress . , progress-.

, (abort, load, or error) loadend:

js
req.addEventListener("loadend", loadEnd);

function loadEnd(e) {
  console.log("   (   ,  ).");
}

, loadend , . , , - .

XMLHttpRequest:

FormData API , , , JSON.stringify. XHR , .

XMLHttpRequest

FormData API API. , , FileReader API.

HTML- <form> :

  • POST enctype application/x-www-form-urlencoded ( );
  • POST enctype text/plain;
  • POST enctype multipart/form-data;
  • GET ( enctype ).

: foo baz. POST, , , , :

  • : POST; : application/x-www-form-urlencoded ( ):

    Content-Type: application/x-www-form-urlencoded
    
    foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A
    
  • : POST; : text/plain:

    Content-Type: text/plain
    
    foo=bar
    baz=The first line.
    The second line.
    
  • : POST; : multipart/form-data:

    Content-Type: multipart/form-data; boundary=---------------------------314911788813839
    
    -----------------------------314911788813839
    Content-Disposition: form-data; name="foo"
    
    bar
    -----------------------------314911788813839
    Content-Disposition: form-data; name="baz"
    
    The first line.
    The second line.
    
    -----------------------------314911788813839--
    

GET, :

?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.

<form>. JavaScript, . XHR , . ( ) , :

html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Sending forms with pure AJAX &ndash; MDN</title>
    <script>
      "use strict";

      // :: XHR Form Submit Framework ::
      //
      // https://developer.mozilla.org/ru/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
      //
      // This framework is released under the GNU Public License, version 3 or later.
      // https://www.gnu.org/licenses/gpl-3.0-standalone.html
      //
      // Syntax:
      //
      // XHRSubmit(HTMLFormElement);
      const XHRSubmit = (function () {
        function xhrSuccess() {
          console.log(this.responseText);
          // you can get the serialized data through the "submittedData" custom property:
          // console.log(JSON.stringify(this.submittedData));
        }

        function submitData(data) {
          const req = new XMLHttpRequest();
          req.submittedData = data;
          req.onload = xhrSuccess;
          if (data.technique === 0) {
            // method is GET
            req.open(
              "get",
              data.receiver.replace(
                /(?:\?.*)?$/,
                data.segments.length > 0 ? `?${data.segments.join("&")}` : "",
              ),
              true,
            );
            req.send(null);
          } else {
            // method is POST
            req.open("post", data.receiver, true);
            if (data.technique === 3) {
              // enctype is multipart/form-data
              const boundary =
                "---------------------------" + Date.now().toString(16);
              req.setRequestHeader(
                "Content-Type",
                `multipart\/form-data; boundary=${boundary}`,
              );
              req.sendAsBinary(
                `--${boundary}\r\n` +
                  data.segments.join(`--${boundary}\r\n`) +
                  `--${boundary}--\r\n`,
              );
            } else {
              // enctype is application/x-www-form-urlencoded or text/plain
              req.setRequestHeader("Content-Type", data.contentType);
              req.send(data.segments.join(data.technique === 2 ? "\r\n" : "&"));
            }
          }
        }

        function processStatus(data) {
          if (data.status > 0) {
            return;
          }
          // the form is now totally serialized! do something before sending it to the server
          // doSomething(data);
          // console.log("XHRSubmit - The form is now serialized. Submitting...");
          submitData(data);
        }

        function pushSegment(segment) {
          this.owner.segments[this.segmentIdx] +=
            segment.target.result + "\r\n";
          this.owner.status--;
          processStatus(this.owner);
        }

        function plainEscape(text) {
          // How should I treat a text/plain form encoding?
          // What characters are not allowed? this is what I suppose:
          // "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2"
          return text.replace(/[\s\=\\]/g, "\\$&");
        }

        function SubmitRequest(target) {
          const isPost = target.method.toLowerCase() === "post";
          this.contentType =
            isPost && target.enctype
              ? target.enctype
              : "application\/x-www-form-urlencoded";
          this.technique = isPost
            ? this.contentType === "multipart\/form-data"
              ? 3
              : this.contentType === "text\/plain"
                ? 2
                : 1
            : 0;
          this.receiver = target.action;
          this.status = 0;
          this.segments = [];
          const filter = this.technique === 2 ? plainEscape : escape;
          for (const field of target.elements) {
            if (!field.hasAttribute("name")) {
              continue;
            }
            const fieldType =
              field.nodeName.toUpperCase() === "INPUT" &&
              field.hasAttribute("type")
                ? field.getAttribute("type").toUpperCase()
                : "TEXT";
            if (fieldType === "FILE" && field.files.length > 0) {
              if (this.technique === 3) {
                // enctype is multipart/form-data
                for (const file of field.files) {
                  const segmReq = new FileReader();

                  // Custom properties:
                  segmReq.segmentIdx = this.segments.length;
                  segmReq.owner = this;

                  segmReq.onload = pushSegment;
                  this.segments.push(
                    'Content-Disposition: form-data; name="' +
                      field.name +
                      '"; filename="' +
                      file.name +
                      '"\r\nContent-Type: ' +
                      file.type +
                      "\r\n\r\n",
                  );
                  this.status++;
                  segmReq.readAsBinaryString(file);
                }
              } else {
                // enctype is application/x-www-form-urlencoded or text/plain or
                // method is GET: files will not be sent!
                for (const file of field.files) {
                  this.segments.push(
                    `${filter(field.name)}=${filter(file.name)}`,
                  );
                }
              }
            } else if (
              (fieldType !== "RADIO" && fieldType !== "CHECKBOX") ||
              field.checked
            ) {
              // NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial.
              // field type is not FILE or is FILE but is empty.
              if (this.technique === 3) {
                // enctype is multipart/form-data
                this.segments.push(
                  `Content-Disposition: form-data; name="${field.name}"\r\n\r\n${field.value}\r\n`,
                );
              } else {
                // enctype is application/x-www-form-urlencoded or text/plain or method is GET
                this.segments.push(
                  `${filter(field.name)}=${filter(field.value)}`,
                );
              }
            }
          }
          processStatus(this);
        }

        return (formElement) => {
          if (!formeElement.action) {
            return;
          }
          new SubmitRequest(formElement);
        };
      })();
    </script>
  </head>
  <body>
    <h1>Sending forms with XHR</h1>

    <h2>Using the GET method</h2>

    <form
      action="register.php"
      method="get"
      >
      <fieldset>
        <legend>Registration example</legend>
        <p>
          <label>First name: <input type="text" name="firstname" /></label
          ><br />
          <label>Last name: <input type="text" name="lastname" /></label>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>

    <h2>Using the POST method</h2>
    <h3>Enctype: application/x-www-form-urlencoded (default)</h3>

    <form
      action="register.php"
      method="post"
      >
      <fieldset>
        <legend>Registration example</legend>
        <p>
          <label>First name: <input type="text" name="firstname" /></label>
          <br />
          <label>Last name: <input type="text" name="lastname" /></label>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>

    <h3>Enctype: text/plain</h3>

    <form
      action="register.php"
      method="post"
      enctype="text/plain"
      >
      <fieldset>
        <legend>Registration example</legend>
        <p>
          <label
            >Your name:
            <input type="text" name="user" />
          </label>
        </p>
        <p>
          <label
            >Your message:<br />
            <textarea name="message" cols="40" rows="8"></textarea>
          </label>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>

    <h3>Enctype: multipart/form-data</h3>

    <form
      action="register.php"
      method="post"
      enctype="multipart/form-data"
      >
      <fieldset>
        <legend>Upload example</legend>
        <p>
          <label>First name: <input type="text" name="firstname" /></label
          ><br />
          <label>Last name: <input type="text" name="lastname" /></label><br />
          Sex:
          <input id="sex_male" type="radio" name="sex" value="male" />
          <label for="sex_male">Male</label>
          <input id="sex_female" type="radio" name="sex" value="female" />
          <label for="sex_female">Female</label><br />
          Password: <input type="password" name="secret" /><br />
          <label
            >What do you prefer:
            <select name="image_type">
              <option>Books</option>
              <option>Cinema</option>
              <option>TV</option>
            </select>
          </label>
        </p>
        <p>
          <label
            >Post your photos:
            <input type="file" multiple name="photos[]" />
          </label>
        </p>
        <p>
          <input
            id="vehicle_bike"
            type="checkbox"
            name="vehicle[]"
            value="Bike" />
          <label for="vehicle_bike">I have a bike</label><br />
          <input
            id="vehicle_car"
            type="checkbox"
            name="vehicle[]"
            value="Car" />
          <label for="vehicle_car">I have a car</label>
        </p>
        <p>
          <label
            >Describe yourself:<br />
            <textarea name="description" cols="50" rows="8"></textarea>
          </label>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>
  </body>
</html>

, register.php ( action ) :

php
<?php
  /* register.php */

  header("Content-type: text/plain");

  /*
  NOTE: You should never use `print_r()` in production scripts, or
  otherwise output client-submitted data without sanitizing it first.
  Failing to sanitize can lead to cross-site scripting vulnerabilities.
  */

  echo ":: data received via GET ::\n\n";
  print_r($_GET);

  echo "\n\n:: Data received via POST ::\n\n";
  print_r($_POST);

  echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
  if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }

  echo "\n\n:: Files received ::\n\n";
  print_r($_FILES);
>

:

js
XHRSubmit(myForm);

: FileReader API . API IE9 . , AJAX . , .

: ArrayBuffers Blobs send() readAsArrayBuffer() FileReader API. , sendAsBinary() readAsBinaryString() FileReader API. , , . , FormData API.

FormData

The FormData constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primary use is in sending form data, but can also be used independently from a form in order to transmit user keyed data. The transmitted data is in the same format the form's submit() method uses to send data, if the form's encoding type were set to "multipart/form-data". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples, and explanations of how one can utilize FormData with XMLHttpRequests, see the Using FormData Objects page. For didactic purposes here is a translation of the previous example transformed to use the FormData API. Note the brevity of the code:

html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Sending forms with FormData &ndash; MDN</title>
    <script>
      "use strict";

      function xhrSuccess () {
        console.log(this.responseText);
      }

      function XHRSubmit (formElement) {
        if (!formElement.action) { return; }
        const req = new XMLHttpRequest();
        req.onload = xhrSuccess;
        if (fFormElement.method.toLowerCase() === "post") {
          req.open("post", formElement.action);
          req.send(new FormData(formElement));
        } else {
          let search = "";
          for (const field of formElement.elements) {
            if (!field.hasAttribute("name")) { continue; }
            const fieldType = field.nodeName.toUpperCase() === "INPUT" && oField.hasAttribute("type")
              ? field.getAttribute("type").toUpperCase()
              : "TEXT";
            if (fieldType === "FILE") {
              for (const file of field.files) {
                search += `&${escape(field.name)}=${escape(file.name)}`;
            } else if ((fieldType !== "RADIO" && fieldType !== "CHECKBOX") || field.checked) {
              search += `&${escape(field.name)}=${escape(field.value)}`;
            }
          }
          req.open("get", formElement.action.replace(/(?:\?.*)?$/, search.replace(/^&/, "?")), true);
          req.send(null);
        }
      }
    </script>
  </head>
  <body>
    <h1>Sending forms with FormData</h1>

    <h2>Using the GET method</h2>

    <form
      action="register.php"
      method="get"
      >
      <fieldset>
        <legend>Registration example</legend>
        <p>
          First name: <input type="text" name="firstname" /><br />
          Last name: <input type="text" name="lastname" />
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>

    <h2>Using the POST method</h2>
    <h3>Enctype: application/x-www-form-urlencoded (default)</h3>

    <form
      action="register.php"
      method="post"
      >
      <fieldset>
        <legend>Registration example</legend>
        <p>
          First name: <input type="text" name="firstname" /><br />
          Last name: <input type="text" name="lastname" />
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>

    <h3>Enctype: text/plain</h3>

    <p>The text/plain encoding is not supported by the FormData API.</p>

    <h3>Enctype: multipart/form-data</h3>

    <form
      action="register.php"
      method="post"
      enctype="multipart/form-data"
      >
      <fieldset>
        <legend>Upload example</legend>
        <p>
          First name: <input type="text" name="firstname" /><br />
          Last name: <input type="text" name="lastname" /><br />
          Sex:
          <input id="sex_male" type="radio" name="sex" value="male" />
          <label for="sex_male">Male</label>
          <input id="sex_female" type="radio" name="sex" value="female" />
          <label for="sex_female">Female</label><br />
          Password: <input type="password" name="secret" /><br />
          What do you prefer:
          <select name="image_type">
            <option>Books</option>
            <option>Cinema</option>
            <option>TV</option>
          </select>
        </p>
        <p>
          Post your photos:
          <input type="file" multiple name="photos[]" />
        </p>
        <p>
          <input
            id="vehicle_bike"
            type="checkbox"
            name="vehicle[]"
            value="Bike" />
          <label for="vehicle_bike">I have a bike</label><br />
          <input
            id="vehicle_car"
            type="checkbox"
            name="vehicle[]"
            value="Car" />
          <label for="vehicle_car">I have a car</label>
        </p>
        <p>
          Describe yourself:<br />
          <textarea name="description" cols="50" rows="8"></textarea>
        </p>
        <p>
          <input type="submit" value="Submit" />
        </p>
      </fieldset>
    </form>
  </body>
</html>

: As we said, FormData objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file <input> fields, when you submit a form through the FormData API you do not need to use the FileReader API also: files are automatically loaded and uploaded.

js
function getHeaderTime() {
  console.log(this.getResponseHeader("Last-Modified")); //   GMTString  null
}

const req = new XMLHttpRequest();
req.open(
  "HEAD", //  HEAD     
  "yourpage.html",
);
req.onload = getHeaderTime;
req.send();

Do something when last modified date changes

Let's create two functions:

js
function getHeaderTime() {
  const lastVisit = parseFloat(
    window.localStorage.getItem(`lm_${this.filepath}`),
  );
  const lastModified = Date.parse(this.getResponseHeader("Last-Modified"));

  if (isNaN(lastVisit) || lastModified > lastVisit) {
    window.localStorage.setItem(`lm_${this.filepath}`, Date.now());
    isFinite(lastVisit) && this.callback(lastModified, lastVisit);
  }
}

function ifHasChanged(URL, callback) {
  const req = new XMLHttpRequest();
  req.open("HEAD" /* use HEAD - we only need the headers! */, URL);
  req.callback = callback;
  req.filepath = URL;
  req.onload = getHeaderTime;
  req.send();
}

And to test:

js
// Let's test the file "yourpage.html"
ifHasChanged("yourpage.html", function (modified, visit) {
  console.log(
    `The page '${this.filepath}' has been changed on ${new Date(
      nModified,
    ).toLocaleString()}!`,
  );
});

If you want to know if the current page has changed, refer to the article about document.lastModified.

XMLHttpRequest

Cross-Origin Resource Sharing (CORS). origin. , INVALID_ACCESS_ERR.

URL- GET-, ?, :

http://foo.com/bar.html -> http://foo.com/bar.html?12345
http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345

, URL, .

:

js
const req = new XMLHttpRequest();

req.open("GET", url + (/\?/.test(url) ? "&" : "?") + new Date().getTime());
req.send(null);

- HTTP- Access-Control-Allow-Origin XMLHttpRequest.

XMLHttpRequests

XMLHttpRequest status=0 statusText=null , . UNSENT. , XMLHttpRequest origin ( XMLHttpRequest) open(). , , XMLHttpRequest, onunload . XMLHttpRequest , , , , ( , open()) , , . - DOMActivate, , unload.

Specification
XMLHttpRequest
# interface-xmlhttprequest


Web Proxy Viewer  |  New URL  |  Original Page