From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- files/de/web/api/xmlhttprequest/index.html | 710 ++++++++++++++++++ .../xmlhttprequest/using_xmlhttprequest/index.html | 789 +++++++++++++++++++++ 2 files changed, 1499 insertions(+) create mode 100644 files/de/web/api/xmlhttprequest/index.html create mode 100644 files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html (limited to 'files/de/web/api/xmlhttprequest') diff --git a/files/de/web/api/xmlhttprequest/index.html b/files/de/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..913acfb17a --- /dev/null +++ b/files/de/web/api/xmlhttprequest/index.html @@ -0,0 +1,710 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequest ist ein JavaScript Objekt, das von Microsoft entwickelt und von Mozilla, Apple, und Google übernommen wurde. Es wird derzeit im W3C standardisiert. Es bietet einen einfachen Weg, Daten von einem URL zu erhalten. Trotz seines Namens kann man mit XMLHttpRequest jede Art von Daten laden, nicht nur XML, und es unterstützt auch andere Protokolle als HTTP (inklusive file und ftp).

+ +

Eine Instanz von XMLHttpRequest erzeugt man ganz einfach so:

+ +
var myRequest = new XMLHttpRequest();
+
+ +

Für Näheres zur Verwendung von XMLHttpRequest, siehe Using XMLHttpRequest.

+ +

Übersicht: Methoden

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XMLHttpRequest(JSObject objParameters);
void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
+ void send(ArrayBuffer data);
+ void send(Blob data);
+ void send(Document data);
+ void send(DOMString? data);
+ void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
Nicht-Standard Methoden
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);
+ +

Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTypBeschreibung
+

onreadystatechange

+
Function? +

Ein JavaScript function Objekt, das bei jedem Wechsel des readyState Attributs aufgerufen wird. Das Callback wird aus dem Thread der Benutzerschnittstelle aufgerufen.

+ +
Warnung: Dies sollte nicht mit synchronen Anfragen und darf nicht aus nativem Code heraus verwendet werden.
+
readyStateunsigned short +

Der Status der Anfrage:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WertStatusBeschreibung
0UNSENTopen()wurde noch nicht aufgerufen.
1OPENEDsend()wurde noch nicht aufgerufen.
2HEADERS_RECEIVEDsend() wurde aufgerufen, und Headers sowie Status sind verfügbar.
3LOADINGDownload ist im Gange; responseText enthält bereits unvollständige Daten.
4DONEDer Vorgang ist abgeschlossen.
+
responsevariiert +

Der Entitätskörper der Antwort (response entity body) gemäss responseType, als ein ArrayBuffer, Blob, {{domxref("Document")}}, JavaScript Objekt (für "json"), oder string. Dies ist null falls die Anfrage nicht abgeschlossen ist oder erfolglos war.

+
responseText {{ReadOnlyInline}}DOMStringDie Antwort auf die Anfrage als Text, oder null falls die Anfrage nicht abgeschlossen ist oder erfolglos war.
responseTypeXMLHttpRequestResponseType +

Kann gesetzt werden, um den Datentyp der Antwort zu ändern.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
WertDatentyp der response Eigenschaft
"" (leerer String)String (Das ist der Default)
"arraybuffer"ArrayBuffer
"blob"{{domxref("Blob")}}
"document"{{domxref("Document")}}
"json"JavaScript Objekt, geparsed aus einem JSON String, der vom Server zurückgegeben wird.
"text"String
"moz-blob"Wird von Firefox verwendet, um den Bezug partieller {{domxref("Blob")}} Daten von progress Events zu erlauben. Dadurch kann ein progress Event Handler bereits mit der Verarbeitung von Daten beginnen, während ihr Empfang noch läuft.
"moz-chunked-text" +

Ähnlich wie "text", aber streamt die Daten. Das bedeutet, dass der Wert in response nur während des "progress" Event verfügbar ist und jeweils nur die Daten enthält, die seit dem letzten "progress" Event eingetroffen sind.

+ +

Wenn auf response während eines "progress" Events zugegriffen wird, enthält es einen String mit den Daten. Andernfalls gibt es null zurück.

+ +

Dieser Modus funktioniert derzeit nur in Firefox.

+
"moz-chunked-arraybuffer" +

Ähnlich wie "arraybuffer", aber streamt die Daten. Das bedeutet, dass der Wert in response nur während des "progress" Event verfügbar ist und jeweils nur die Daten enthält, die seit dem letzten "progress" Event eingetroffen sind.

+ +

Wenn auf response während eines "progress" Events zugegriffen wird, enthält es einen ArrayBuffer mit den Daten. Andernfalls gibt es null zurück.

+ +

Dieser Modus funktioniert derzeit nur in Firefox.

+
+ +
Anmerkung: Ab Gecko 11.0  sowie WebKit build 528 kann man in diesen Browsern das responseType Attribut nicht mehr für synchrone Anfragen benutzen. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus. Diese Änderung wurde dem W3C zur Standardisierung vorgeschlagen.
+
responseXML {{ReadOnlyInline}}Document? +

Die Antwort auf die Anfrage als DOM Document Objekt, oder null falls die Anfrage erfolglos war, noch nicht gesendet wurde, oder nicht als XML oder HTML geparst werden kann. Die Antwort wird geparst, als wäre sie ein text/xml Stream. Wenn der responseType auf "document" gesetzt wurde und die Anfrage asynchron gemacht wurde, wird die Antwort geparst, als wäre sie ein text/html Stream.

+ +
Anmerkung: Falls der Server nicht den text/xml Inhaltstyp-Header auf die Antwort anwendet, kann man overrideMimeType() verwenden, um XMLHttpRequest zu zwingen, sie dennoch als XML zu parsen.
+
status {{ReadOnlyInline}}unsigned shortDer Status der Antwort auf die Anfrage. Das ist der HTTP Ergebnis-Code (status ist z.B. 200 für eine erfolgreiche Anfrage).
statusText {{ReadOnlyInline}}DOMStringDer Antwort-String, der vom HTTP Server zurückgesendet wurde. Im Gegensatz zu status beinhaltet dies den ganzen Text der Antwortnachricht (z.B. "200 OK").
timeoutunsigned long +

Die Anzahl Millisekunden, die eine Anfrage dauern darf, bevor sie automatisch abgebrochen wird. Ein Wert von 0 (das ist die Voreinstellung) bedeutet, dass es kein timeout gibt.

+ +
Anmerkung: Für synchrone Anfragen mit einem besitzenden Fenster darf man kein timeout verwenden.
+
uploadXMLHttpRequestUploadDas Hochladen kann mitverfolgt werden, indem man einen Event Listener zu upload hinzufügt.
withCredentialsboolean +

Zeigt an, ob Site-übergreifende Access-Control Anfragen mit Credentials wie Cookies oder Autorisierungs-Headers durchgeführt werden sollen oder nicht. Die Voreinstellung ist false.

+ +
Anmerkung: Anfragen an die ursprüngliche Site sind davon niemals betroffen.
+ +
Anmerkung: Ab Gecko 11.0 kann man das withCredentials Attribut nicht mehr für synchrone Anfragen verwenden. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus.
+
+ +

Nicht-Standard Eigenschaften

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributTypDescription
channel {{ReadOnlyInline}}{{Interface("nsIChannel")}}Der Kanal, der vom Objekt zur Durchführung der Anfrage verwendet wurde. Das ist null falls der Kanal noch nicht erzeugt worden ist. Im Falle von mehrteiligen Anfragen ist das der anfängliche Kanal, nicht derjenige der anderen Teile der mehrteiligen Anfrage.
+ Zugriff nur mit erhöhten Rechten.
mozAnon {{ReadOnlyInline}}boolean +

Falls true wird die Anfrage ohne Cookie und Authentisierungs-Headers gesendet.

+
mozSystem {{ReadOnlyInline}}boolean +

Falls true wird die Regel, die nur Anfragen zum gleichen Ursprung erlaubt, für diese Anfrage nicht durchgesetzt.

+
mozBackgroundRequestboolean +

Zeigt an, ob das Objekt eine Service-Anfrage im Hintergrund darstellt. Falls true wird keine Lastgruppe mit der Anfrage verknüpft, und die Anzeige von Sicherheits-Dialogen wird verhindert. Zugriff nur mit erhöhten Rechten.

+ +

In Fällen, wo normalerweise ein Sicherheits-Dialog angezeigt würde (wie Autorisierungs- oder Zertifikatsfehler-Benachrichtigungen), schlägt die Anfrage stattdessen einfach fehl.

+ +
Anmerkung: Diese Eigenschaft muss vor dem Aufrufen von open() gesetzt werden..
+
mozResponseArrayBuffer  {{obsolete_inline("6")}} {{ReadOnlyInline}}ArrayBufferDie Antwort auf die Anfrage, als typisiertes JavaScript Array. Dies ist NULL falls die Anfrage erfolglos war oder noch nicht gesendet wurde.
multipart {{obsolete_inline("22")}}boolean +

Dieses nur in Gecko verfügbare Feature wurde in Firefox/Gecko 22 entfernt. Bitte verwende stattdessen Server-Sent Events, Web Sockets oder responseText aus progress Events.

+ +

Zeigt an, ob als Antwort ein Stream von möglicherweise mehreren XML Dokumenten erwartet wird. Wird dies auf true gesetzt, muss der Inhaltstyp des ersten Teils der Antwort multipart/x-mixed-replace sein, sonst tritt ein Fehler auf. Alle Anfragen müssen asynchron sein.

+ +

Dies ermöglicht die Unterstützung von Server Push; für jedes XML Dokument, das in die Antwort auf diese Anfrage geschrieben wird, wird ein neues XML DOM Dokument erzeugt, und zwischen den Dokumenten wird der onload Handler aufgerufen.

+ +
Anmerkung: Wenn dies gesetzt ist, werden onload und andere Event Handler nicht zurückgesetzt, nachdem das erste XML Dokument geladen ist, und der onload Handler wird nach Erhalt jedes Teils der Antwort aufgerufen.
+
+ +

Konstruktor

+ +

XMLHttpRequest()

+ +

Der Konstruktor initiiert ein XMLHttpRequest Objekt. Er muss vor allen anderen Methoden aufgerufen werden.

+ +

Gecko/Firefox 16 fügt einen nicht-standard Parameter zum Konstruktor hinzu, der den anonymen Modus einschalten kann (siehe Bug 692677). Das mozAnon flag auf true zu setzen, hat einen ähnlichen Effekt wie der AnonXMLHttpRequest() Konstruktor, der in der XMLHttpRequest Spezifikation beschrieben ist, aber noch in keinem Browser implementiert wurde (Stand September 2012).

+ +
XMLHttpRequest (
+  JSObject objParameters
+);
+ +
Parameter (nicht-standard)
+ +
+
objParameters
+
Es gibt zwei Flags, die gesetzt werden können: +
+
mozAnon
+
Boolean: Wenn dieses Flag auf true gesetzt ist, wird der Browser weder den Ursprung der Anfrage noch Anmeldedaten übermitteln, wenn er Daten anfordert. Das heisst vor allem auch, dass keine Cookies gesendet werden, sofern sie nicht ausdrücklich mit setRequestHeader hinzugefügt wurden.
+
mozSystem
+
Boolean: Dieses Flag auf true zu setzen, ermöglicht das Herstellen von Cross-Site Verbindungen, ohne dass der Server dem mittels CORS zustimmen muss. Erfodert das Setzen von mozAnon: true. D.h. das kann nicht mit dem Senden von Cookies oder anderen Anmeldeinformationen kombiniert werden. Dies funktioniert nur in privilegierten (reviewed) Apps; es klappt nicht auf beliebigen Webseiten, die in Firefox geladen werden.
+
+
+
+ +

Methoden

+ +

abort()

+ +

Bricht die Anfrage ab, falls sie bereits gesendet wurde.

+ +

getAllResponseHeaders()

+ +
DOMString getAllResponseHeaders();
+ +

Liefert alle Antwort-Header als String, oder null falls keine Antwort empfangen wurde.

+ +

Anmerkung: Für mehrteilige Anfragen gibt dies die Header des aktuellen Teils der Anfrage zurück, nicht die des ursprünglichen Kanals.

+ +

getResponseHeader()

+ +
DOMString? getResponseHeader(DOMString header);
+ +

Liefert den String mit dem Text des angegebenen Headers, oder null falls die Antwort noch nicht empfangen wurde oder der Header in der Antwort nicht existiert.

+ +

open()

+ +

Initialisiert eine Anfrage. Diese Methode ist nur zur Verwendung in JavaScript Code; um eine Anfrage aus nativem Code zu initialisieren, ist stattdessen openRequest() zu benutzen.

+ +
Anmerkung: Der Aufruf dieser Methode für eine bereits aktive Anfrage (eine, für die open()oder openRequest() schon ausgeführt wurde) ist gleichwertig mit  dem Aufruf von abort().
+ +
void open(
+   DOMString method,
+   DOMString url,
+   optional boolean async,
+   optional DOMString user,
+   optional DOMString password
+);
+
+ +
Parameter
+ +
+
method
+
Die zu benutzende HTTP Methode,  wie "GET", "POST", "PUT", "DELETE", etc. Wird für nicht-HTTP(S) URLs ignoriert.
+
url
+
Der URL, an den die Anfrage geschickt werden soll.
+
async
+
Ein optionaler boole'scher Parameter mit Defaultwert true, der angibt, ob die Operation asynchron ausgeführt werden soll. Wenn dieser Wert false ist, kehrt die send()Methode nicht zurück, bis die Antwort vollständig empfangen worden ist. Ist er true, kehrt sie sofort zurück, und die Benachrichtigung über die vollendete Transaktion erfolgt mittels Events. Dies muss true sein falls das multipart Attribut true ist, sonst wird ein Fehler ausgelöst.
+
user
+
Der optionale Benutzername zum Zweck der Authentisierung; ohne Angabe ist dies ein leerer String.
+
password
+
Das optionale Passwort zum Zweck der Authentisierung; ohne Angabe ist dies ein leerer String.
+
+ +

overrideMimeType()

+ +

Übergeht den vom Server zurückgegebenen MIME Typ. Dies kann beispielsweise benutzt werden, um zu erzwingen, dass ein Stream als text/xml behandelt und geparst wird, selbst wenn ihn der Server nicht als das meldet. Diese Methode muss vor send() aufgerufen werden.

+ +
void overrideMimeType(DOMString mimetype);
+ +

send()

+ +

Sendet die Anfrage. Falls die Anfage asynchron ist (was der Default ist), kehrt diese Methode zurück, sobald die Anfrage gesendet ist. Ist die Anfrage synchron, kehrt diese Methode nicht zurück, bis die Antwort angekommen (oder ein Timeout aufgetreten) ist.

+ +
Anmerkung: Jegliche zu setzende Event Handler / Listener müssen vor dem Aufruf von send() gesetzt werden.
+ +
void send();
+void send(ArrayBuffer data);
+void send(Blob data);
+void send(Document data);
+void send(DOMString? data);
+void send(FormData data);
+ +
Anmerkungen
+ +

Falls data ein Document ist, so wird dieses vor dem Senden serialisiert. Beim Senden eines Document senden Firefox Versionen vor Version 3 die Anfrage immer encodiert als UTF-8; Firefox 3 sendet das Document richtigerweise mit dem angegebenen body.xmlEncoding, oder UTF-8 falls keines angegeben wurde.

+ +

Falls es ein nsIInputStream ist, muss er kompatibel sein mit der setUploadStream()Methode des nsIUploadChannel. In diesem Fall wird die Länge des Inhalts in einem Content-Length Header zur Anfrage hinzugefügt, dessen Wert mit der available()Methode des nsIInputStream ermittelt wird. Jegliche Header, die am Anfang des Streams enthalten sind, werden als Teil des Nachrichtenkörpers behandelt. Der MIME Typ des Streams sollte vor dem Aufruf von send() angegeben werden, indem der Content-Type Header mit der  setRequestHeader() Methode gesetzt wird.

+ +

Der beste Weg, um binäre Inhalte zu senden (wie beim Hochladen einer Datei), ist die Verwendung von ArrayBuffern oder Blobs in Verbindung mit der send() Methode. Wenn jedoch stringifizierbare Rohdaten gesendet werden sollen, ist die sendAsBinary() Methode zu verwenden.

+ +

setRequestHeader()

+ +

Setzt den Wert eines HTTP Anfrage-Headers. Aufrufe von setRequestHeader() müssen nach open(), aber vor send() erfolgen.

+ +
void setRequestHeader(
+   DOMString header,
+   DOMString value
+);
+
+ +
Parameter
+ +
+
header
+
Der Name des zu setzenden Headers.
+
value
+
Der Wert des zu setzenden Headers.
+
+ +

Nicht-Standard Methoden

+ +

init()

+ +

Initialisiert das Objekt für die Verwendung aus C++ Code.

+ +
Warnung: Diese Methode darf nicht aus JavaScript heraus aufgerufen werden.
+ +
[noscript] void init(
+   in nsIPrincipal principal,
+   in nsIScriptContext scriptContext,
+   in nsPIDOMWindow ownerWindow
+);
+
+ +
Parameter
+ +
+
principal
+
Das Prinzipal, das für die Anfrage benutzt werden soll; darf nicht null sein.
+
scriptContext
+
Der Skript-Kontext, der für die Anfrage benutzt werden soll; darf nicht null sein.
+
ownerWindow
+
Das Fenster, das zu der Anfrage gehört; darf null sein.
+
+ +

openRequest()

+ +

Initialisiert eine Anfrage. Diese Methode ist zur Verwendung in nativem Code; um eine Anfrage in JavaScript Code zu initialisieren, ist stattdessen open() zu verwenden. Siehe Dokumentation für open().

+ +

sendAsBinary()

+ +

Eine Variante der send() Methode, die binäre Daten schickt.

+ +
void sendAsBinary(
+   in DOMString body
+);
+
+ +

Diese Methode, zusammen mit der readAsBinaryString Methode der FileReader API, ermöglichen das Lesen und den Upload jeglicher Dateitypen und das Stringifizieren der Rohdaten.

+ +
Parameter
+ +
+
body
+
Der Körper der Anfrage als DOMstring. Diese Daten werden durch Beschneiden (Entfernen des höherwertigen Bytes jedes Zeichens) in Einzel-Byte-Zeichen umgewandelt.
+
+ +
sendAsBinary() polyfill
+ +

Da sendAsBinary() ein experimentelles Feature ist, kommt hier ein Polyfill für Browser, die sendAsBinary() nicht unterstützen, dafür aber typisierte Arrays.

+ +
/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+|*|
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* sende als ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...oder als ArrayBuffer (altmodisch)...: this.send(ui8Data.buffer); */
+  };
+}
+ +
Anmerkung: Dieses Polyfill kann mit zwei Datentypen als Argument für send() gebaut werden: einem ArrayBuffer (ui8Data.buffer – kommentierter Code) oder einer ArrayBufferView (ui8Data, das ist ein typisiertes Array von 8-bit Ganzzahlen ohne Vorzeichen – unkommentierter Code). Wenn man jedoch in Google Chrome versucht, einen ArrayBuffer zu senden, erscheint die folgende Warnmeldung: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.
+ +

Anmerkungen

+ + + +

Events

+ +

onreadystatechange als eine Eigenschaft der XMLHttpRequest Instanz wird von allen Browsern unterstützt.

+ +

Seither wurden einige zusätzliche Event Handler in verschiedenen Browsern implementiert (onload, onerror, onprogress, etc.). Diese werden in Firefox unterstützt. Für Genaueres, siehe {{interface("nsIXMLHttpRequestEventTarget")}} und Using XMLHttpRequest.

+ +

Neuere Browser, inklusive Firefox, unterstützen das 'Horchen' nach XMLHttpRequest Ereignissen mittels der Standard addEventListener APIs zusätzlich zum Setzen von on* Eigenschaften auf eine Handler Funktion.

+ +

Browser Kompatibilität

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Grundsätzliche Unterstützung (XHR1)11.05 (via ActiveXObject)
+ 7 (XMLHttpRequest)
{{CompatVersionUnknown}}1.2
send(ArrayBuffer)99{{compatUnknown}}11.60{{compatUnknown}}
send(Blob)73.6{{compatUnknown}}12{{compatUnknown}}
send(FormData)64{{compatUnknown}}12{{compatUnknown}}
sendAsBinary(DOMString){{compatNo}} – benutze polyfill1.9{{compatUnknown}}{{compatUnknown}}{{compatUnknown}}
response1061011.60{{compatUnknown}}
responseType = 'arraybuffer'1061011.60{{compatUnknown}}
responseType = 'blob'1961012{{compatUnknown}}
responseType = 'document'181110{{CompatNo}}{{CompatNo}}
responseType = 'json'{{CompatNo}}10{{CompatNo}}12{{CompatNo}}
Progress Events73.51012{{compatUnknown}}
withCredentials33.510124
timeout{{CompatNo}}12.08{{compatUnknown}}{{CompatNo}}
responseType = 'moz-blob'{{CompatNo}}12.0{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome für AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Grundsätzliche Unterstützung{{CompatUnknown}}0.16{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Gecko Anmerkungen

+ +

Gecko 11.0 {{geckoRelease("11.0")}} entfernte die Unterstützung für die Verwendung der responseType und withCredentials Attribute bei der Durchführung synchroner Anfragen. Der Versuch löst einen NS_ERROR_DOM_INVALID_ACCESS_ERR Fehler aus. Diese Änderung wurde dem W3C zur Standardisierung vorgeschlagen.

+ +

Gecko 12.0 {{geckoRelease("12.0")}} und spätere unterstützen die Verwendung von XMLHttpRequest zum Lesen von data: URLs.

+ +

Siehe auch

+ + diff --git a/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..f15901a388 --- /dev/null +++ b/files/de/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,789 @@ +--- +title: Using XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +
{{APIRef ("XMLHttpRequest")}}
+ +

In diesem Handbuch wird erläutert, wie Sie mit {{domxref ("XMLHttpRequest")}} HTTP- Anforderungen ausgeben , um Daten zwischen der Website und einem Server auszutauschen . Beispiele für häufig vorkommende und unklarere Anwendungsfälle XMLHttpRequestsind enthalten.

+ +

Um eine HTTP-Anfrage zu senden, erstellen Sie ein XMLHttpRequestObjekt, öffnen Sie eine URL und senden Sie die Anfrage. Nach Abschluss der Transaktion enthält das Objekt nützliche Informationen wie den Antworttext und den HTTP-Status des Ergebnisses.

+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

Arten von Anfragen

+ +
+

Eine Anforderung über XMLHttpRequestkann die Daten auf zwei Arten asynchron oder synchron abrufen. Die Art der Anforderung wird durch das optionale asyncArgument (das dritte Argument) bestimmt, das für die Methode {{domxref ("XMLHttpRequest.open ()")}} festgelegt wird. Wenn dieses Argument angegeben ist trueoder nicht, XMLHttpRequestwird das asynchron verarbeitet, andernfalls wird der Prozess synchron behandelt. Eine ausführliche Diskussion und Demonstration dieser beiden Arten von Anforderungen finden Sie auf der Seite für synchrone und asynchrone Anforderungen . Verwenden Sie keine synchronen Anforderungen außerhalb von Web Workers.

+
+ +
Hinweis: Ab Gecko 30.0 {{geckoRelease ("30.0")}} sind synchrone Anforderungen im Hauptthread aufgrund der negativen Auswirkungen auf die Benutzererfahrung veraltet.
+ +
Hinweis: Die Konstruktorfunktion XMLHttpRequestist nicht nur auf XML-Dokumente beschränkt. Es beginnt mit "XML", da das Hauptformat, das ursprünglich für den asynchronen Datenaustausch verwendet wurde, bei der Erstellung XML war
+ +

Umgang mit Antworten

+ +

Es gibt verschiedene Arten von Antwortattributen, die durch die Living Standard-Spezifikation für den Konstruktor {{domxref ("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest ()")}} definiert sind. Diese teilen dem Kunden die XMLHttpRequestwichtigen Informationen über den Status der Antwort mit. In den folgenden Abschnitten werden einige Fälle beschrieben, in denen der Umgang mit Nicht-Text-Antworttypen möglicherweise manipuliert und analysiert wird.

+ +

Analysieren und Bearbeiten der responseXML-Eigenschaft

+ +

If you use XMLHttpRequest to get the content of a remote XML document, the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} property will be a DOM object containing a parsed XML document. This could prove difficult to manipulate and analyze. There are four primary ways of analyzing this XML document:

+ +
    +
  1. Using XPath to address (or point to) parts of it.
  2. +
  3. Manually Parsing and serializing XML to strings or objects.
  4. +
  5. Using {{domxref("XMLSerializer")}} to serialize DOM trees to strings or to files.
  6. +
  7. {{jsxref("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 line breaks. However, this method is a "last resort" since if the XML code changes slightly, the method will likely fail.
  8. +
+ +
+

Note: XMLHttpRequest can now interpret HTML for you using the {{domxref("XMLHttpRequest.responseXML", "responseXML")}} property. Read the article about HTML in XMLHttpRequest to learn how to do this.

+
+ +

Processing a responseText property containing an HTML document

+ +

If you use XMLHttpRequest to get the content of a remote HTML webpage, the {{domxref("XMLHttpRequest.responseText", "responseText")}} property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string:

+ +
    +
  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. +
  3. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  4. +
  5. {{jsxref("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.
  6. +
+ +

Handling binary data

+ +

Although {{domxref("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 {{domxref("XMLHttpRequest.overrideMimeType", "overrideMimeType()")}} method on the XMLHttpRequest object and is a workable solution.

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

However, more modern techniques are available, since the {{domxref("XMLHttpRequest.responseType", "responseType")}} attribute now supports a number of additional content types, which makes sending and receiving binary data much easier.

+ +

For example, consider this snippet, which uses the responseType of "arraybuffer" to fetch the remote content into a {{jsxref("ArrayBuffer")}} object, which stores the raw binary data.

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

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

+ +

Monitoring progress

+ +

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 {{event("progress")}} event monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the {{domxref("ProgressEvent")}} interface. The actual events you can monitor to determine the state of an ongoing transfer are:

+ +
+
{{event("progress")}}
+
The amount of data that has been retrieved has changed.
+
{{event("load")}}
+
The transfer is complete; all data is now in the response
+
+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load", transferComplete);
+oReq.addEventListener("error", transferFailed);
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// progress on transfers from the server to the client (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total * 100;
+    // ...
+  } else {
+    // Unable to compute progress information since the total size is unknown
+  }
+}
+
+function transferComplete(evt) {
+  console.log("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  console.log("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  console.log("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.

+ +
Note: 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 oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress);
+oReq.upload.addEventListener("load", transferComplete);
+oReq.upload.addEventListener("error", transferFailed);
+oReq.upload.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+ +
Note: Progress events are not available for the file: protocol.
+ +
+

Note: Starting in {{Gecko("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.

+
+ +
+

Note: As of {{Gecko("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);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

Note there is 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.

+ +

Submitting forms and uploading files

+ +

Instances of XMLHttpRequest can be used to submit forms in two ways:

+ + + +

Using the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified.
+ Using only AJAX is more complex, but typically more flexible and powerful.

+ +

Using nothing but XMLHttpRequest

+ +

Submitting forms without the FormData API does not require other APIs for most use cases. The only case where you need an additional API is if you want to upload one or more files, where you use the {{domxref("FileReader")}} API.

+ +

A brief introduction to the submit methods

+ +

An html {{ HTMLElement("form") }} can be sent in four ways:

+ + + +

Now, consider the submission of a form containing only two fields, named foo and baz. If you are using the POST method the server will receive a string similar to one of the following three examples, depending on the encoding type you are using:

+ + + +

However, if you are using the GET method, a string like the following will be simply added to the URL:

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

A little vanilla framework

+ +

All these effects are done automatically by the web browser whenever you submit a {{HTMLElement("form")}}. If you want to perform the same effects using JavaScript you have to instruct the interpreter about everything. Therefore, how to send forms in pure AJAX is too complex to be explained here in detail. For this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with pure AJAX &ndash; MDN</title>
+<script type="text/javascript">
+
+"use strict";
+
+/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polyfill ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function(sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+
+/*\
+|*|
+|*|  :: AJAX Form Submit Framework ::
+|*|
+|*|  https://developer.mozilla.org/en-US/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:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    console.log(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* console.log(JSON.stringify(this.submittedData)); */
+  }
+
+  function submitData (oData) {
+    /* the AJAX request... */
+    var oAjaxReq = new XMLHttpRequest();
+    oAjaxReq.submittedData = oData;
+    oAjaxReq.onload = ajaxSuccess;
+    if (oData.technique === 0) {
+      /* method is GET */
+      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/,
+          oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
+      oAjaxReq.send(null);
+    } else {
+      /* method is POST */
+      oAjaxReq.open("post", oData.receiver, true);
+      if (oData.technique === 3) {
+        /* enctype is multipart/form-data */
+        var sBoundary = "---------------------------" + Date.now().toString(16);
+        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
+        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" +
+            oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
+      } else {
+        /* enctype is application/x-www-form-urlencoded or text/plain */
+        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
+        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
+      }
+    }
+  }
+
+  function processStatus (oData) {
+    if (oData.status > 0) { return; }
+    /* the form is now totally serialized! do something before sending it to the server... */
+    /* doSomething(oData); */
+    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
+    submitData (oData);
+  }
+
+  function pushSegment (oFREvt) {
+    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
+    this.owner.status--;
+    processStatus(this.owner);
+  }
+
+  function plainEscape (sText) {
+    /* 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 sText.replace(/[\s\=\\]/g, "\\$&");
+  }
+
+  function SubmitRequest (oTarget) {
+    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
+    /* console.log("AJAXSubmit - Serializing form..."); */
+    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
+    this.technique = bIsPost ?
+        this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
+    this.receiver = oTarget.action;
+    this.status = 0;
+    this.segments = [];
+    var fFilter = this.technique === 2 ? plainEscape : escape;
+    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
+      oField = oTarget.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE" && oField.files.length > 0) {
+        if (this.technique === 3) {
+          /* enctype is multipart/form-data */
+          for (nFile = 0; nFile < oField.files.length; nFile++) {
+            oFile = oField.files[nFile];
+            oSegmReq = new FileReader();
+            /* (custom properties:) */
+            oSegmReq.segmentIdx = this.segments.length;
+            oSegmReq.owner = this;
+            /* (end of custom properties) */
+            oSegmReq.onload = pushSegment;
+            this.segments.push("Content-Disposition: form-data; name=\"" +
+                oField.name + "\"; filename=\"" + oFile.name +
+                "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
+            this.status++;
+            oSegmReq.readAsBinaryString(oFile);
+          }
+        } else {
+          /* enctype is application/x-www-form-urlencoded or text/plain or
+             method is GET: files will not be sent! */
+          for (nFile = 0; nFile < oField.files.length;
+              this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
+        }
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.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 */
+        this.segments.push(
+          this.technique === 3 ? /* enctype is multipart/form-data */
+            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
+          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
+            fFilter(oField.name) + "=" + fFilter(oField.value)
+        );
+      }
+    }
+    processStatus(this);
+  }
+
+  return function (oFormElement) {
+    if (!oFormElement.action) { return; }
+    new SubmitRequest(oFormElement);
+  };
+
+})();
+
+</script>
+</head>
+<body>
+
+<h1>Sending forms with pure AJAX</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <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" onsubmit="AJAXSubmit(this); return false;">
+  <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>
+
+<form action="register.php" method="post" enctype="text/plain"
+    onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      Your name: <input type="text" name="user" />
+    </p>
+    <p>
+      Your message:<br />
+      <textarea name="message" cols="40" rows="8"></textarea>
+    </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"
+    onsubmit="AJAXSubmit(this); return false;">
+  <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>
+
+ +

To test this, create a page named register.php (which is the action attribute of these sample forms), and put the following minimalistic content:

+ +
<?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);
+
+
+ +

The syntax to activate this script is simply:

+ +
AJAXSubmit(myForm);
+ +
Note: This framework uses the {{domxref("FileReader")}} API to transmit file uploads. This is a recent API and is not implemented in IE9 or below. For this reason, the AJAX-only upload is considered an experimental technique. If you do not need to upload binary files, this framework works fine in most browsers.
+ +
Note: The best way to send binary content is via {{jsxref("ArrayBuffer", "ArrayBuffers")}} or {{domxref("Blob", "Blobs")}} in conjuncton with the {{domxref("XMLHttpRequest.send()", "send()")}} method and possibly the {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} method of the FileReader API. But, since the aim of this script is to work with a stringifiable raw data, we used the {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} method in conjunction with the {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} method of the FileReader API. As such, the above script makes sense only when you are dealing with small files. If you do not intend to upload binary content, consider instead using the FormData API.
+ +
Note: The non-standard sendAsBinary method is considered deprecated as of Gecko 31 {{geckoRelease(31)}} and will be removed soon. The standard send(Blob data) method can be used instead.
+ +

Using FormData objects

+ +

The {{domxref("XMLHttpRequest.FormData", "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:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" charset="UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script>
+"use strict";
+
+function ajaxSuccess () {
+  console.log(this.responseText);
+}
+
+function AJAXSubmit (oFormElement) {
+  if (!oFormElement.action) { return; }
+  var oReq = new XMLHttpRequest();
+  oReq.onload = ajaxSuccess;
+  if (oFormElement.method.toLowerCase() === "post") {
+    oReq.open("post", oFormElement.action);
+    oReq.send(new FormData(oFormElement));
+  } else {
+    var oField, sFieldType, nFile, sSearch = "";
+    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
+      oField = oFormElement.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ?
+          oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE") {
+        for (nFile = 0; nFile < oField.files.length;
+            sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
+      }
+    }
+    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
+    oReq.send(null);
+  }
+}
+</script>
+</head>
+<body>
+
+<h1>Sending forms with FormData</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <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" onsubmit="AJAXSubmit(this); return false;">
+  <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"
+    onsubmit="AJAXSubmit(this); return false;">
+  <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>
+
+ +
Note: As we said, {{domxref("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 {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the {{domxref("FileReader")}} API also: files are automatically loaded and uploaded.
+ +

Get last modified date

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
+oReq.onload = getHeaderTime;
+oReq.send();
+ +

Do something when last modified date changes

+ +

Let's create two functions:

+ +
function getHeaderTime () {
+  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
+  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
+
+  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
+    window.localStorage.setItem('lm_' + this.filepath, Date.now());
+    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
+  }
+}
+
+function ifHasChanged(sURL, fCallback) {
+  var oReq = new XMLHttpRequest();
+  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

And to test:

+ +
/* Let's test the file "yourpage.html"... */
+
+ifHasChanged("yourpage.html", function (nModif, nVisit) {
+  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
+});
+ +

If you want to know if the current page has changed, please read the article about {{domxref("document.lastModified")}}.

+ +

Cross-site XMLHttpRequest

+ +

Modern browsers support cross-site requests by implementing the Cross-Origin Resource Sharing (CORS) 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

+ +

A cross-browser compatible approach to bypassing the cache is appending a timestamp to the URL, being sure to include a "?" or "&" as appropriate. For example:

+ +
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
+
+ +

As 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 oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
+oReq.send(null);
+ +

Security

+ +

{{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 conclude with an XMLHttpRequest receiving status=0 and statusText=null, this means 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 subsequently open(). This case can happen, for example, when one has an XMLHttpRequest that gets fired on an onunload event for a window, the expected XMLHttpRequest is created when the window to be closed is still there, and finally sending the request (in otherwords, open()) when this window has lost its focus and another window gains focus. The most effective way to avoid this problem is to set a listener on the new window's {{event("activate")}} event which is set once the terminated window has its {{event("unload")}} event triggered.

+ +

Workers

+ +

Setting overrideMimeType does not work from a {{domxref("Worker")}}. See {{bug(678057)}} for more details. Other browsers may handle this differently.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +

{{Compat ("api.XMLHttpRequest")}}

+ +

Siehe auch

+ +
    +
  1. MDN AJAX Einführung
  2. +
  3. HTML in XMLHttpRequest
  4. +
  5. HTTP-Zugriffskontrolle
  6. +
  7. So überprüfen Sie den Sicherheitsstatus einer XMLHTTPRequest über SSL
  8. +
  9. XMLHttpRequest - REST und die Rich User Experience
  10. +
  11. Microsoft-Dokumentation
  12. +
  13. "Verwenden des XMLHttpRequest-Objekts" (jibbering.com)
  14. +
  15. Das XMLHttpRequestObjekt: WHATWG-Spezifikation
  16. +
-- cgit v1.2.3-54-g00ecf