Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 671677 of XMLHttpRequest の利用

  • リビジョンの URL スラグ: Web/API/XMLHttpRequest/Using_XMLHttpRequest
  • リビジョンのタイトル: XMLHttpRequest の利用
  • リビジョンの ID: 671677
  • 作成日:
  • 作成者: taiyaki32
  • 現行リビジョン? いいえ
  • コメント

このリビジョンの内容

{{translationinprogress}}
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', 'https://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 {{HTMLElement("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_callout_heading("9.0")}}

Starting in Gecko 9.0 {{geckoRelease("9.0")}}, 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_callout_heading("12.0")}}

If your progress event is called with a responseType of "moz-blob", the value of response is a {{domxref("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:

https://foo.com/bar.html

becomes

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

and

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

becomes

https://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); 

セキュリティ

{{fx_minversion_note(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.")}}

{{fx_minversion_note(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)

このリビジョンのソースコード

<div>
 {{translationinprogress}}</div>
<div>
 <a href="/ja/docs/DOM/XMLHttpRequest" title="XMLHttpRequest"><code>XMLHttpRequest</code></a>を使うとHTTPリクエストをとても簡単に送信できます.単にオブジェクトのインスタンスを生成し.URLをオープンして,リクエストを送信するだけです.トランザクションが完了すると, 結果の<a href="/ja/docs/HTTP/HTTP_response_codes" title="HTTP response codes">HTTP status</a>と内容をリクエストオブジェクトから取得できます.本ページでは、この強力なJavaScriptオブジェクトのユースケースについて、一般的なものからあまり知られていないものまで、概観します.</div>
<div>
 &nbsp;</div>
<div>
 (以下原文)</div>
<p><a href="/ja/docs/DOM/XMLHttpRequest" title="XMLHttpRequest"><code>XMLHttpRequest</code></a> makes sending HTTP requests very easy. You simply create an instance of the object, open a URL, and send the request. The <a href="/ja/docs/HTTP/HTTP_response_codes" title="HTTP response codes">HTTP status</a> 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.</p>
<h2 id="Types_of_requests" name="Types_of_requests">リクエストタイプ</h2>
<p>XMLHttpRequest経由で作成されたリクエストは,非同期または同期のいずれかの方法でデータを取得することが可能です.リクエストをどちらの方法で行うのかは、XMLHttpRequest <a href="/ja/docs/DOM/XMLHttpRequest#open" title="DOM/XMLHttpRequest#open()">.open()</a>メソッドの<code>async</code>プロパティで指示できます(オプション).このプロパティをfalseにセットするとXMLHttpRequestは同期処理となります.それ以外だと非同期処理になります.これら2種類のリクエストの詳細および使用例は,<a href="/ja/docs/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" title="Synchronous and Asynchronous Requests">同期および非同期リクエスト</a>のページを参照してください.<br />
 <br />
 (以下原文)<br />
 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 <code>async</code> property that is set on the XMLHttpRequest <a href="/ja/docs/DOM/XMLHttpRequest#open" title="DOM/XMLHttpRequest#open()">.open()</a> 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 <a href="/ja/docs/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" title="Synchronous and Asynchronous Requests">synchronous and asynchronous requests</a> page.</p>
<h2 id="Handling_responses" name="Handling_responses">レスポンスハンドリング</h2>
<p>There are several types of <a href="https://www.w3.org/TR/XMLHttpRequest2/#response" title="https://www.w3.org/TR/XMLHttpRequest2/#response">response attributes</a> 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:</p>
<div style="overflow:hidden">
 <pre class="brush: js" id="line1">
var request = new XMLHttpRequest();
request.open('GET', 'https://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);
}</pre>
</div>
<p>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.</p>
<h3 id="Analyzing_and_manipulating_the_responseXML_property" name="Analyzing_and_manipulating_the_responseXML_property"><code>responseXML</code>&nbsp;プロパティの分析と操作</h3>
<p>If you use <code>XMLHttpRequest </code>to get the content of a remote XML document, the <code>responseXML </code>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:</p>
<ol>
 <li>Using <a href="/ja/docs/XPath" title="XPath">XPath</a> to address (point to) parts of it.</li>
 <li>Using <a href="/ja/docs/JXON" title="JXON">JXON</a> to convert it into a JavaScript Object tree.</li>
 <li>Manually <a href="/ja/docs/Parsing_and_serializing_XML" title="Parsing_and_serializing_XML">Parsing and serializing XML</a> to strings or objects.</li>
 <li>Using <a href="/ja/docs/XMLSerializer" title="XMLSerializer">XMLSerializer</a> to serialize <strong>DOM trees to strings or to files</strong>.</li>
 <li><a href="/ja/docs/JavaScript/Reference/Global_Objects/RegExp" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp">RegExp </a>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.</li>
</ol>
<h3 id="Analyzing_and_manipulating_a_responseText_property_containing_an_HTML_document" name="Analyzing_and_manipulating_a_responseText_property_containing_an_HTML_document">HTML ドキュメントを含む<code>responseText</code> プロパティの分析と操作</h3>
<div class="note">
 <strong>注記:</strong> The W3C <a href="https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">XMLHttpRequest</a> specification has added <strong>HTML parsing support to <a href="/ja/docs/DOM/XMLHttpRequest" title="DOM/XMLHttpRequest"><code>XMLHttpRequest</code></a></strong>, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using <code>XMLHttpRequest.<strong>responseXML</strong></code> property. Read the article about <a href="/ja/docs/HTML_in_XMLHttpRequest" title="HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a> for details.</div>
<p>If you use <code>XMLHttpRequest</code> to get the content of a remote HTML webpage, the <code>responseText</code> 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:</p>
<ol>
 <li><a href="/ja/docs/Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM" title="Code_snippets/HTML_to_DOM#Safely_parsing_simple_HTML.c2.a0to_DOM">Safely parsing with nsIScriptableUnescapeHTML</a> will quickly convert the HTML string into DOM, while stripping out JavaScript and other advanced elements, including the <code>&lt;head&gt;</code> of the webpage.</li>
 <li><a href="/ja/docs/JavaScript/Reference/Global_Objects/RegExp" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp">RegExp </a>can be used if you always know the content of the HTML <code>responseText </code>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.</li>
 <li><a href="/ja/docs/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window%27s_DOM" title="https://developer.mozilla.org/en/Code_snippets/HTML_to_DOM#Using_a_hidden_iframe_element_to_parse_HTML_to_a_window's_DOM">Using a hidden chrome or content-level iframe</a> to load up the webpage can also be done to then manipulate it as DOM, however there are <a href="/ja/docs/Displaying_web_content_in_an_extension_without_security_issues" title="Displaying_web_content_in_an_extension_without_security_issues">security risks to giving remote code this level of privileged access</a>, which can cause <a class="link-https" href="https://addons.mozilla.org/en-US/developers/docs/policies/reviews" title="https://addons.mozilla.org/en-US/developers/docs/policies/reviews">issues </a>for the review of your addon. For example, if a webpage executes the common "<code>document.location = redirecttothispage.html</code>" command on load, this will get interpreted as changing the browser chrome location (<code>document.location</code> in an extension) as opposed to the webpage location (<code>content.document.location</code> in an extension), thus destroying all browser components. Alternatively, and somewhat safer, a <code>responseText </code>string attained through a <code>XMLHttpRequest </code>can be analyzed using RegExp to remove potential JavaScript problems, then loaded into the hidden iframe that you have set up:</li>
</ol>
<pre>
document.getElementById("hiddenXULiframe").contentWindow.document.body.innerHTML = req.responseText
</pre>
<h2 id="Using_FormData_objects" name="Using_FormData_objects">Using FormData objects</h2>
<p>The <a href="/ja/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> object lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. 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 <code>submit()</code> 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 <a href="/ja/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects" title="Using FormData Objects">Using FormData Objects</a> page.</p>
<h2 id="Sending_forms_through_the_URL_string" name="Sending_forms_through_the_URL_string">Sending forms through the URL string</h2>
<p><strong>When a {{HTMLElement("form")}} uses the <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3" title="https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3"><code>GET</code></a> <a href="/ja/docs/DOM/form.method" title="HTML/Element/form#attr-method">method</a></strong>, you can send its content directly through the URL string:</p>
<pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDN Example &amp;ndash; AJAX and forms&lt;/title&gt;
&lt;script type="text/javascript"&gt;
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 &lt; aFields.length; nItem++) {
    oField = aFields[nItem];
    if (!oField.hasAttribute("name") || (/^(?:radio|checkbox)$/.test(oField.type) &amp;&amp; !oField.checked)) { continue; }
    sGet += "&amp;" + 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);
}
&lt;/script&gt;

&lt;/head&gt;
 
&lt;body&gt;

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

&lt;/body&gt;
&lt;/html&gt;</pre>
<h2 id="Handling_binary_data" name="Handling_binary_data">バイナリデータハンドリング</h2>
<p>Although <code>XMLHttpRequest</code> 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.</p>
<pre class="brush: js">
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// retrieve data unprocessed as a binary string
xhr.overrideMimeType("text/plain; charset=x-user-defined");
/* ... */
</pre>
<p>The XMLHttpRequest Level 2 Specification adds new <a href="https://www.w3.org/TR/XMLHttpRequest2/#the-responsetype-attribute" title="https://www.w3.org/TR/XMLHttpRequest2/#the-responsetype-attribute">responseType attributes</a> which make sending and receiving binary data much easier.</p>
<pre class="brush: js">
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer"; 
xhr.onload = function(e) {
  var arraybuffer = xhr.response; // not responseText
  /* ... */
}
xhr.send();
</pre>
<p>For more examples check out the <a href="/ja/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data" title="DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data">Sending and Receiving Binary Data</a> page</p>
<h2 id="Monitoring_progress" name="Monitoring_progress">プロセス監視</h2>
<p><code>XMLHttpRequest</code> 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.</p>
<p>Support for DOM progress event monitoring of <code>XMLHttpRequest</code> transfers follows the Web API <a href="https://dev.w3.org/2006/webapi/progress/Progress.html" title="https://dev.w3.org/2006/webapi/progress/Progress.html">specification for progress events</a>.</p>
<pre class="brush: js">
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.");
}
</pre>
<p>Lines 3-6 add event listeners for the various events that are sent while performing a data transfer using <code>XMLHttpRequest</code>.</p>
<div class="note">
 <strong>注記:</strong> You need to add the event listeners before calling <code>open()</code> on the request. Otherwise the progress events will not fire.</div>
<p>The progress event handler, specified by the <code>updateProgress()</code> 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 <code>total</code> and <code>loaded</code> fields. However, if the <code>lengthComputable</code> field is false, the total length is not known and will be zero.</p>
<p>Progress events exist for both download and upload transfers. The download events are fired on the <code>XMLHttpRequest</code> object itself, as shown in the above sample. The upload events are fired on the <code>XMLHttpRequest.upload</code> object, as shown below:</p>
<pre class="brush: js">
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();
</pre>
<div class="note">
 <strong>注記:</strong> Progress events are not available for the <code>file:</code> protocol.</div>
<div class="geckoVersionNote" style="undefined">
 <p>{{gecko_callout_heading("9.0")}}</p>
 <p>Starting in Gecko 9.0 {{geckoRelease("9.0")}}, 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.</p>
</div>
<div class="geckoVersionNote">
 <p>{{gecko_callout_heading("12.0")}}</p>
 <p>If your progress event is called with a <code>responseType</code> of "moz-blob", the value of response is a {{domxref("Blob")}} containing the data received so far.</p>
</div>
<p>One can also detect all three load-ending conditions (<code>abort</code>, <code>load</code>, or <code>error</code>) using the <code>loadend</code> event:</p>
<pre class="brush: js">
req.addEventListener("loadend", loadEnd, false);

function loadEnd(evt) {
  alert("The transfer finished (although we don't know if it succeeded or not).");
} 
</pre>
<p>Note that there's no way to be certain from the information received by the <code>loadend</code> 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.</p>
<h2 id="Cross-site_XMLHttpRequest" name="Cross-site_XMLHttpRequest">Cross-site XMLHttpRequest</h2>
<p>Modern browsers support cross-site requests by implementing the web applications working group's <a href="/ja/docs/HTTP_access_control" title="HTTP access control">Access Control for Cross-Site Requests</a> standard. As long as the server is configured to allow requests from your web application's origin, <code>XMLHttpRequest</code> will work. Otherwise, an <code>INVALID_ACCESS_ERR</code> exception is thrown.</p>
<h2 id="Bypassing_the_cache" name="Bypassing_the_cache">Bypassing the cache</h2>
<p>Normally, <code>XMLHttpRequest</code> tries to retrieve content from the cache, if it's available. To bypass this, do the following:</p>
<pre class="brush: js">
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
req.send(null);</pre>
<div class="note">
 <strong>注記:</strong> This approach will only work in Gecko-based software, as the <code>channel</code> attribute is Gecko-specific.</div>
<p>An alternate, cross-browser compatible approach is to append a timestamp to the URL, being sure to include a "?" or "&amp;" as appropriate. For example:</p>
<pre>
https://foo.com/bar.html</pre>
<p>becomes</p>
<pre>
https://foo.com/bar.html?12345</pre>
<p>and</p>
<pre>
https://foo.com/bar.html?foobar=baz</pre>
<p>becomes</p>
<pre>
https://foo.com/bar.html?foobar=baz&amp;12345</pre>
<p>Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.</p>
<p>You can automatically adjust URLs using the following code:</p>
<pre class="brush: js">
var req = new XMLHttpRequest();
req.open("GET", url += ((/\?/).test(url) ? "&amp;" : "?") + (new Date()).getTime(), false);
req.send(null); </pre>
<h2 id="Security" name="Security">セキュリティ</h2>
<p>{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference <code>capability.policy.<policyname>.XMLHttpRequest.open</policyname></code> to <code>allAccess</code> to give specific sites cross-site access. This is no longer supported.")}}</p>
<p>{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use <code>netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");</code> to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}</p>
<p>The recommended way to enable cross-site scripting is to use the <code>Access-Control-Allow-Origin </code> HTTP header in the response to the XMLHttpRequest.</p>
<h3 id="XMLHttpRequests_being_stopped" name="XMLHttpRequests_being_stopped">XMLHttpRequests being stopped</h3>
<p>If you end up with an XMLHttpRequest having <code>status=0</code> and <code>statusText=null</code>, it means that the request was not allowed to be performed. It was <code><a href="https://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-unsent" title="https://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-unsent">UNSENT</a></code>. A likely cause for this is when the <a href="https://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest-origin" style="outline: 1px dotted; outline-offset: 0pt;"><code>XMLHttpRequest</code> origin</a> (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then <code>open()</code>. 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 <code>open()</code>) 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.</p>
<h2 id="Downloading_JSON_and_JavaScript_from_extensions" name="Downloading_JSON_and_JavaScript_from_extensions">Downloading JSON and JavaScript from extensions</h2>
<p>For security reasons, extensions should never use <code><a href="/ja/docs/JavaScript/Reference/Global_Objects/eval" title="JavaScript/Reference/Global_Functions/eval">eval()</a></code> to parse JSON or JavaScript code downloaded from the web. See <a href="/ja/docs/Downloading_JSON_and_JavaScript_in_extensions" title="Downloading_JSON_and_JavaScript_in_extensions">Downloading JSON and JavaScript in extensions</a> for details.</p>
<h2 id="Using_XMLHttpRequest_from_JavaScript_modules_.2F_XPCOM_components" name="Using_XMLHttpRequest_from_JavaScript_modules_.2F_XPCOM_components">Using XMLHttpRequest from JavaScript modules / XPCOM components</h2>
<p>Instantiating <code>XMLHttpRequest</code> from a <a href="/ja/docs/JavaScript_code_modules/Using" title="https://developer.mozilla.org/en/JavaScript_code_modules/Using_JavaScript_code_modules">JavaScript module</a> or an XPCOM component works a little differently; it can't be instantiated using the <code>XMLHttpRequest()</code> 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.</p>
<pre class="brush: js">
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
var req = XMLHttpRequest();</pre>
<p>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.</p>
<pre class="brush: js">
const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
                                     .getService(Components.interfaces.nsIAppShellService)
                                     .hiddenDOMWindow;
var req = XMLHttpRequest();
</pre>
<h2 id="See_also" name="See_also">関連情報</h2>
<ol>
 <li><a href="/ja/docs/AJAX/Getting_Started" title="AJAX/Getting_Started">MDC AJAX introduction</a></li>
 <li><a href="/ja/docs/HTTP_access_control" title="HTTP access control">HTTP access control</a></li>
 <li><a href="/ja/docs/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL" title="How to check the security state of an XMLHTTPRequest over SSL">How to check the security state of an XMLHTTPRequest over SSL</a></li>
 <li><a href="https://www.peej.co.uk/articles/rich-user-experience.html">XMLHttpRequest - REST and the Rich User Experience</a></li>
 <li><a href="https://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmobjxmlhttprequest.asp">Microsoft documentation</a></li>
 <li><a href="https://developer.apple.com/internet/webcontent/xmlhttpreq.html">Apple developers' reference</a></li>
 <li><a href="https://jibbering.com/2002/4/httprequest.html">"Using the XMLHttpRequest Object" (jibbering.com)</a></li>
 <li><a href="https://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object: W3C Specification</a></li>
 <li><a href="https://dev.w3.org/2006/webapi/progress/Progress.html" title="https://dev.w3.org/2006/webapi/progress/Progress.html">Web Progress Events specification</a></li>
 <li><a href="https://www.bluishcoder.co.nz/2009/06/05/reading-ogg-files-with-javascript.html" title="https://www.bluishcoder.co.nz/2009/06/05/reading-ogg-files-with-javascript.html">Reading Ogg files with JavaScript (Chris Double)</a></li>
</ol>
このリビジョンへ戻す