XMLHttpRequest の利用

この文書は翻訳中です。他国語のままの部分などがあるのはその為です。
是非お気軽に MDN に登録して翻訳に参加し、私たちの手助けをして下さい!

XMLHttpRequestで大変簡単にHTTPリクエストを送信できます.あなたは単にオブジェクトのインスタンスを生成し.URLをオープンして,リクエストを送信するだけです.結果の内容と同様に,結果のHTTP statusは,トランザクションが完了した時点でリクエストオブジェクト内で利用可能になります.本ページではこの強力なJavaScriptオブジェクトに関する,いくつかの一般的な利用事例を概観します(少し曖昧な利用事例も含みます).
 
(以下原文)

XMLHttpRequest makes sending HTTP requests very easy. You simply create an instance of the object, open a URL, and send the request. The HTTP status of the result, as well as the result's contents, are available in the request object when the transaction is completed. This page outlines some of the common and even slightly obscure use cases for this powerful JavaScript object.

リクエストタイプ

XMLHttpRequest経由で作成されたリクエストは,非同期または同期のいずれかの方法でデータを取得することが可能です.リクエストの型はXMLHttpRequest .open()メソッドでセットされるオプションのasyncプロパティで指示します.このプロパティをfalseにセットするとXMLHttpRequestは同期処理となります.それ以外は処理は非同期に行われます.これら2つの型のリクエストの詳細および事例は,同期および非同期リクエストのページを参照してください.

(以下原文)
A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async property that is set on the XMLHttpRequest .open() method. If this property is set to false, then the XMLHttpRequest will be processed synchronously, otherwise the process will be done asynchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page.

レスポンスハンドリング

There are several types of response attributes defined by the W3C specification for XMLHttpRequest. These tell the client making the XMLHttpRequest important information about the status of the response. For many use cases this is as straightforward as the following example:

var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // because of "false" above, will block until the request is done 
                // and status is available. Not recommended, however it works for simple cases.

if (request.status === 200) {
  console.log(request.responseText);
}

There are some situations where the contents of a remote response from an XMLHttpRequest may not be handled as easily as the case above. A few of these cases where dealing with reponseXML and responseText involves some manipulation and analysis are outlined in the following sections.

responseXML プロパティの分析と操作

If you use XMLHttpRequest to get the content of a remote XML document, the responseXML property will be a DOM Object containing a parsed XML document, which can be hard to manipulate and analyze. There are four primary ways of analyzing this XML document:

  1. Using XPath to address (point to) parts of it.
  2. Using JXON to convert it into a JavaScript Object tree.
  3. Manually Parsing and serializing XML to strings or objects.
  4. Using XMLSerializer to serialize DOM trees to strings or to files.
  5. RegExp can be used if you always know the content of the XML document beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.

HTML ドキュメントを含むresponseText プロパティの分析と操作

注記: The W3C XMLHttpRequest specification has added HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.responseXML property. Read the article about HTML in XMLHttpRequest for details.

If you use XMLHttpRequest to get the content of a remote HTML webpage, the responseText property is a string containing a "soup" of all the HTML tags, which can be hard to manipulate and analyze. There are three primary ways of analyzing this HTML soup string:

  1. Safely parsing with nsIScriptableUnescapeHTML will quickly convert the HTML string into DOM, while stripping out JavaScript and other advanced elements, including the <head> of the webpage.
  2. RegExp can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.
  3. Using a hidden chrome or content-level iframe to load up the webpage can also be done to then manipulate it as DOM, however there are security risks to giving remote code this level of privileged access, which can cause issues for the review of your addon. For example, if a webpage executes the common "document.location = redirecttothispage.html" command on load, this will get interpreted as changing the browser chrome location (document.location in an extension) as opposed to the webpage location (content.document.location in an extension), thus destroying all browser components. Alternatively, and somewhat safer, a responseText string attained through a XMLHttpRequest can be analyzed using RegExp to remove potential JavaScript problems, then loaded into the hidden iframe that you have set up:
document.getElementById("hiddenXULiframe").contentWindow.document.body.innerHTML = req.responseText

Using FormData objects

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the 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.

Sending forms through the URL string

When a <form> uses the GET method, you can send its content directly through the URL string:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example &ndash; AJAX and forms</title>
<script type="text/javascript">
function AJAXSuccess () {
  alert(this.responseText);
}

function AJAXError (oError) {
  alert("An error occurred, please try again.");
}

function AJAXGet (oForm) {
  if (oForm.method.toLowerCase() !== "get") { return; }
  var sGet = "", aFields = oForm.elements, oReq = new XMLHttpRequest();
  for (var oField, nItem = 0; nItem < aFields.length; nItem++) {
    oField = aFields[nItem];
    if (!oField.hasAttribute("name") || (/^(?:radio|checkbox)$/.test(oField.type) && !oField.checked)) { continue; }
    sGet += "&" + escape(oField.getAttribute("name")) + "=" + escape(oField.value);
  }
  oReq.onload = AJAXSuccess;
  oReq.onerror = AJAXError;
  oReq.open("get", sGet ? oForm.action + "?" + sGet.slice(1) : oForm.action, true);
  oReq.send(null);
}
</script>

</head>
 
<body>

  <form onsubmit="return AJAXGet(this), false;" action="test.php" method="get">
    <p>
      First name: <input type="text" name="firstname" /><br />
      Last name: <input type="text" name="lastname" /><br />
      Password: <input type="password" name="pwd" /><br />
      <input type="radio" name="sex" value="male" /> Male
      <input type="radio" name="sex" value="female" /> Female
    </p>
    <p>
      <input type="checkbox" name="vehicle" value="Bike" />I have a bike<br />
      <input type="checkbox" name="vehicle" value="Car" />I have a car
    </p>
    <p>
      <input type="submit" value="Submit" />
    </p>
  </form>

</body>
</html>

バイナリデータハンドリング

Although XMLHttpRequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. There are several well tested methods for coercing the response of an XMLHttpRequest into sending binary data. These involve utilizing the .overrideMimeType() method on the XMLHttpRequest object and is a workable solution.

var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
/* ... */

The XMLHttpRequest Level 2 Specification adds new responseType attributes which make sending and receiving binary data much easier.

var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer"; 
xhr.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  /* ... */
}
xhr.send();

For more examples check out the Sending and Receiving Binary Data page

プロセス監視

XMLHttpRequest provides the ability to listen to various events that can occur while the request is being processed. This includes periodic progress notifications, error notifications, and so forth.

Support for DOM progress event monitoring of XMLHttpRequest transfers follows the Web API specification for progress events.

var req = new XMLHttpRequest();

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

req.open();

...

// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    ...
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

function transferComplete(evt) {
  alert("The transfer is complete.");
}

function transferFailed(evt) {
  alert("An error occurred while transferring the file.");
}

function transferCanceled(evt) {
  alert("The transfer has been canceled by the user.");
}

Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using XMLHttpRequest.

注記: You need to add the event listeners before calling open() on the request. Otherwise the progress events will not fire.

The progress event handler, specified by the updateProgress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero.

Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

var req = new XMLHttpRequest();

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

req.open();
注記: Progress events are not available for the file: protocol.

Gecko 9.0 note
(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6)

Starting in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), progress events can now be relied upon to come in for every chunk of data received, including the last chunk in cases in which the last packet is received and the connection closed before the progress event is fired. In this case, the progress event is automatically fired when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event.

Gecko 12.0 note
(Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9)

If your progress event is called with a responseType of "moz-blob", the value of response is a Blob containing the data received so far.

One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:

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

function loadEnd(evt) {
  alert("The transfer finished (although we don't know if it succeeded or not).");
} 

Note that there's no way to be certain from the information received by the loadend event as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios.

Cross-site XMLHttpRequest

Modern browsers support cross-site requests by implementing the web applications working group's Access Control for Cross-Site Requests standard. As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work. Otherwise, an INVALID_ACCESS_ERR exception is thrown.

Bypassing the cache

Normally, XMLHttpRequest tries to retrieve content from the cache, if it's available. To bypass this, do the following:

var req = new XMLHttpRequest();
req.open('GET', url, false);
req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
req.send(null);
注記: This approach will only work in Gecko-based software, as the channel attribute is Gecko-specific.

An alternate, cross-browser compatible approach is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:

http://foo.com/bar.html

becomes

http://foo.com/bar.html?12345

and

http://foo.com/bar.html?foobar=baz

becomes

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

Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

You can automatically adjust URLs using the following code:

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

セキュリティ

Firefox 3 における注記

Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy.<policyname>.XMLHttpRequest.open</policyname> to allAccess to give specific sites cross-site access. This is no longer supported.

Firefox 5 における注記

Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

XMLHttpRequests being stopped

If you end up with an XMLHttpRequest having status=0 and statusText=null, it means that the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then open(). This case can happen for example when one has an XMLHttpRequest that gets fired on an onunload event for a window: the XMLHttpRequest gets in fact created when the window to be closed is still there, and then the request is sent (ie open()) when this window has lost its focus and potentially different window has gained focus. The way to avoid this problem is to set a listener on the new window "activate" event that gets set when the old window has its "unload" event fired.

Downloading JSON and JavaScript from extensions

For security reasons, extensions should never use eval() to parse JSON or JavaScript code downloaded from the web. See Downloading JSON and JavaScript in extensions for details.

Using XMLHttpRequest from JavaScript modules / XPCOM components

Instantiating XMLHttpRequest from a JavaScript module or an XPCOM component works a little differently; it can't be instantiated using the XMLHttpRequest() constructor. The constructor is not defined inside components and the code results in an error. The best way to work around this is to use the XPCOM component constructor.

const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
var req = XMLHttpRequest();

Unfortunately in versions of Gecko prior to Gecko 16 there is a bug which can cause requests created this way to be cancelled for no reason. If you need your code to work on Gecko 15 or earlier, you can get the XMLHttpRequest constructor from the hidden DOM window like so.

const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
                                     .getService(Components.interfaces.nsIAppShellService)
                                     .hiddenDOMWindow;
var req = XMLHttpRequest();

関連情報

  1. MDC AJAX introduction
  2. HTTP access control
  3. How to check the security state of an XMLHTTPRequest over SSL
  4. XMLHttpRequest - REST and the Rich User Experience
  5. Microsoft documentation
  6. Apple developers' reference
  7. "Using the XMLHttpRequest Object" (jibbering.com)
  8. The XMLHttpRequest Object: W3C Specification
  9. Web Progress Events specification
  10. Reading Ogg files with JavaScript (Chris Double)

Document Tags and Contributors

Contributors to this page: saneyuki_s, ethertank, maco81, Potappo, acid, SoutaTakada
最終更新者: acid,