В процессе перевода.
XMLHttpRequest это API которое позволяет передавать данные со стороны клиента на сервер без перезагрузки страницы. XMLHttpRequest используется в AJAX запросах и особенно в single-page приложениях.
Не смотря на свое название, XMLHttpRequest может быть использован для получения данных в различных текстовых форматах, таких как json, xml, текст (вобще, при помощи XMLHttpRequest можно получить даже бинарные данные, другое дело, как эти данные отобразить для клиента). Кроме этого запрос выполняется с использованием различных протоколов, отличных от HTTP (ftp, например).
Чтобы начать работать с XMLHttpRequest, выполните этот код:
var myRequest = new XMLHttpRequest();
более детальное описание создание объекта, можно увидеть в разделе Using XMLHttpRequest.
Список методов объекта
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(ArrayBufferView data);void send(Blob data);void send(Document data);void send(DOMString? data);void send(FormData data); |
void setRequestHeader(DOMString header, DOMString value); |
| Не стандартизированные методы |
|---|
[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); Устарело Gecko 31 |
Поля объекта
| Attribute | Type | Description | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Function? |
Callback - функция, которая вызывается всякий раз, когда поле Внимание: Он не должен использоваться в синхронных запросах, и не должен выполняться из нативного кода (? must not be used from native code).
|
||||||||||||||||||||
readyState |
unsigned short |
Состояние запроса:
|
||||||||||||||||||||
response |
varies |
Тело сущности запроса. Соласно полю |
||||||||||||||||||||
responseText Read only |
DOMString |
Ответ на запрос в виде строки, или null в случае ели запрос не успешен, или ответ еще не получен. |
||||||||||||||||||||
responseType |
XMLHttpRequestResponseType |
Может быть утсановлен для того, чтобы определить тип ответа.
Note: Starting with Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8), as well as WebKit build 528, these browsers no longer let you use the
responseType attribute when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception. This change has been proposed to the W3C for standardization. |
||||||||||||||||||||
responseXML Read only |
Document? |
Ответ является объектом DOM Примечание: Если сервер не работаетс заголовком (не присылает в ответе) "Content-type:
text/xml", то можно использовать метод overrideMimeType() для того чтобы парсить получаемый ответ как XML. |
||||||||||||||||||||
status Read only |
unsigned short |
Статус ответа на запрос. Равен кодам HTTP (200 - успешно, 404 не найдено, 301 - перенесено навсегда). | ||||||||||||||||||||
statusText Read only |
DOMString |
Строка статуса ответа. В отличи от поля status, эта строка включает в себя текст - ("200 OK", например). |
||||||||||||||||||||
timeout |
unsigned long |
Время в миллисекундах, после которого запрос будет отменен. Значение 0 (по умолчанию) значит что таймаута не будет. Никогда. Примечание: Вы можете не использовать поле timeout для синхронных запросов из owning window.
|
||||||||||||||||||||
ontimeout |
Function |
Колбек - функция которая будет вызвана в случае таймаута. |
||||||||||||||||||||
upload |
XMLHttpRequestUpload |
Загрзка (upload process) может отслеживаться event listener'ом. | ||||||||||||||||||||
withCredentials |
boolean |
Определяет что cross-site запрос, согласно Примечание: Не влияет на same-site запросы.
Примечание: Начиная с Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8), Gecko больше не позволяет использовать поле
withCredentials при выполнении синхроных запросов. Попытка выполнить это выбрасывает NS_ERROR_DOM_INVALID_ACCESS_ERR исключение. |
Non-standard properties
| Attribute | Type | Description |
|---|---|---|
channel Read only |
nsIChannel |
The channel used by the object when performing the request. This is null if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. Requires elevated privileges to access. |
mozAnon Read only |
boolean |
If true, the request will be sent without cookie and authentication headers. |
mozSystem Read only |
boolean |
If true, the same origin policy will not be enforced on the request. |
mozBackgroundRequest |
boolean |
This method is not available from Web content. It requires elevated privileges to access. Indicates whether or not the object represents a background service request. If In cases in which a security dialog (such as authentication or a bad certificate notification) would normally be shown, the request simply fails instead. Note: This property must be set before calling
open(). |
mozResponseArrayBuffer Вышла из употребления с версии Gecko 6 Read only |
ArrayBuffer |
The response to the request, as a JavaScript typed array. This is NULL if the request was not successful, or if it hasn't been sent yet. |
multipart Вышла из употребления с версии Gecko 22 |
boolean |
This Gecko-only feature was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or Indicates whether or not the response is expected to be a stream of possibly multiple XML documents. If set to This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the Note: When this is set, the
onload handler and other event handlers are not reset after the first XMLdocument is loaded, and the onload handler is called after each part of the response is received. |
Конструктор
XMLHttpRequest()
Конструктор создает объект XMLHttpRequest. Он должен быть вызван перед образением к любому методу класса.
Gecko/Firefox 16 добавляет не стандартные параметры в конструктор, для лучшего взаимодействия с режимом инкогнито, (смотри Bug 692677). Установка флага mozAnon в значение true создает сущность AnonXMLHttpRequest() описанную в XMLHttpRequest спецификации, но не реализованную не в одном из браузеров (информация сентября 2012).
XMLHttpRequest ( JSObject objParameters );
Параметры (не стантдартные)
objParameters- Вы можете использовать два флага:
mozAnon- Boolean: Использование этого флага уберет из запроса заголовки origin, и user credentials. Кроме этого, куки не будут отправлены в запросе, если только они не будут добавлены к запросу специально, через метод setRequestHeader.
mozSystem- Boolean: Если выставить этот флаг в значение
trueто это позволит делать cross-доменные запросы без необходимости получения специальных заголовков со стороны сервера (CORS). Для использования этого флага необходимо использовать дополнительный флагmozAnon: true, поскольку для отправки запросаа на другой домен, нельзя использовать куки и креды польщователя. Этот флаг работает только с привелегированными (одобренными) приложениями; он не сработает с произвольно загруженными страницами.
Методы
abort()
Отменяет запрос, если он был отправлен.
getAllResponseHeaders()
DOMString getAllResponseHeaders();
Возвращает все заголовки ответа как строку, или null если ответ не все еще не пришел. Для multypart запросов возвращает заголовки текущей части запроса, а не всего канала.
getResponseHeader()
DOMString? getResponseHeader(DOMString header);
Возвращает значение указанноаго заголовка из полученного ответа, или null в случает если ответ не получен, или такого заголовка в ответе нет. Возвращаемая строка имеет кодировку UTF.
Примечание: Если в ответе есть заголовки с одни названием, то значения этих заголовков будут объеденены в одну строку, разделенную запятой и пробелом.
open()
Инициализирует запрос. Этот метод может (и должен) быть вызван из JavaScript кода; если необходимо вызвать запрос из нативного кода, то нужно использовать метод openRequest().
open() или openRequest() уже были вызваны) эквивалентно вызову метода abort().void open( DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password );
Параметры
method- HTTP метод отправки сообщения - "GET", "POST", "PUT", "DELETE", и проч. Ignored for non-HTTP(S) URLs.
url- URL адрес, на который будет отправлено сообщение.
async- Необязательный boolean параметр, по умолчанию равный
true. Определяет, будет ли запрос отправлен асинхронно. Если значение равноfalse, методsend() вернет ответ в общем потоке работы приложения (иначе говоря, приложение зависнет на некоторое время), в противном случае, ответ может быть получен только при помощи определенныхevent listener'ов. В случае, если используется отправкаmultipartзапроса, то этот аттруибут должен бытьtrue, или будет выбрашено исключение.Примечаени: Начиная с Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), синхронные запросы объявлены как deprecated, в силу того что все пользователи недовольны тем, что приложение "зависает". user- Необязательный параметр, используется для аутентификации пользователя. По умолчанию, пустая строка.
password- Необязательный параметр, используется для аутентификации пользователя. По умолчанию пустая строка.
overrideMimeType()
Переопределяет MIME тип, получаемый от сервера. Это может быть использовано, например, для того чтобы получить и распарсить данные в формате text/xml, даже, если сервер сообщает что это не так. Этот метод должен быть вызван перед вызовом метода send().
void overrideMimeType(DOMString mimetype);
send()
Отправляет запрос. Если запрос асинхронный (а по умолчанию это так), этот метод вернет значение сразу после того как метод вызван.
Примечание переводчика: в этом случае, в ответе не будет содержаться информации, которая пришла с сервера, поскольку она еще не пришла. Для того чтобы получить эту информацию, нужно слушать события загрузки, или использовать promise.
Если запрос синхронный, то метод вернет значение только после того, как придет запрос от сервера.
send().XMLHttpRequest. Вместо него можно использовать ArrayBufferView (смотри табицу совместимостей для различных версий).void send();void send(ArrayBuffer data);void send(ArrayBufferView data); void send(Blob data); void send(Document data); void send(DOMString? data); void send(FormData data);
Примечания
Если тип data - Document, то он будет сериализован перед отправкой. Firefox до версии 3 всегда отправляет такой запрос в кодировке UTF-8; Firefox 3 отправляет данные в той кодировке, которая указаны в body.xmlEncoding, или UTF-8 если такой информации нет.
If it's an nsIInputStream, it must be compatible with nsIUploadChannel's setUploadStream()method. In that case, a Content-Length header is added to the request, with its value obtained using nsIInputStream's available()method. Any headers included at the top of the stream are treated as part of the message body. The stream's MIMEtype should be specified by setting the Content-Type header using the setRequestHeader() method prior to calling send().
The best way to send binary content (like in files upload) is using an ArrayBufferView or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView Non native typed arrays superclass.
setRequestHeader()
Sets the value of an HTTP request header. You must call setRequestHeader() after open(), but before send(). If this method is called several times with the same header, the values are merged into one single request header.
void setRequestHeader( DOMString header, DOMString value );
Parameters
header- The name of the header whose value is to be set.
value- The value to set as the body of the header.
Non-standard methods
init()
Initializes the object for use from C++ code.
[noscript] void init( in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow );
Parameters
principal- The principal to use for the request; must not be
null. scriptContext- The script context to use for the request; must not be
null. ownerWindow- The window associated with the request; may be
null.
openRequest()
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open()instead. See the documentation for open().
sendAsBinary()
Устарело Gecko 31A variant of the send() method that sends binary data.
send(Blob data) method can be used instead.void sendAsBinary( in DOMString body );
This method, used in conjunction with the readAsBinaryString method of the FileReader API, makes it possible to read and upload any type of file and to stringify the raw data.
Parameters
body- The request body as a DOMstring. This data is converted to a string of single-byte characters by truncation (removing the high-order byte of each character).
sendAsBinary() polyfill
Since sendAsBinary() is an experimental feature, here is a polyfill for browsers that don't support the sendAsBinary() method but support typed 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;
}
/* send as ArrayBufferView...: */
this.send(ui8Data);
/* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
};
}
send(): an ArrayBuffer (ui8Data.buffer – the commented code) or an ArrayBufferView (ui8Data, which is a typed array of 8-bit unsigned integers – uncommented code). However, on Google Chrome, when you try to send an ArrayBuffer, the following warning message will appear: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead. Another possible approach to send binary data is the StringView Non native typed arrays superclass in conjunction with the send() method.Notes
- By default, Firefox 3 limits the number of
XMLHttpRequestconnections per server to 6 (previous versions limit this to 2 per server). Some interactive web sites may keep anXMLHttpRequestconnection open, so opening multiple sessions to such sites may result in the browser hanging in such a way that the window no longer repaints and controls don't respond. This value can be changed by editing thenetwork.http.max-persistent-connections-per-serverpreference inabout:config. - From Gecko 7.0 headers set by
setRequestHeader()are sent with the request when following a redirect. Previously these headers would not be sent. XMLHttpRequestis implemented in Gecko using thensIXMLHttpRequest,nsIXMLHttpRequestEventTarget, andnsIJSXMLHttpRequestinterfaces.- When a request reaches its timeout value, a "timeout" event is raised.
Events
onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.
Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.
More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.
Permissions
When using System XHR via the mozSystem property, for example for Firefox OS apps, you need to be sure to add the systemXHR permission into your manifest file. System XHR can be used in privileged or certified apps.
"permissions": {
"systemXHR":{}
}
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support (XHR1) | 1 | 1.0 | 5 (via ActiveXObject) 7 (XMLHttpRequest) |
(Да) | 1.2 |
send(ArrayBuffer) |
9 | 9 | 10 | 11.60 | ? |
send(ArrayBufferView) |
22 | 20 | ? | ? | ? |
send(Blob) |
7 | 3.6 | 10 | 12 | ? |
send(FormData) |
6 | 4 | 10 | 12 | ? |
sendAsBinary(DOMString) |
Нет – use the polyfill | 1.9 | Нет | Нет | Нет |
response |
10 | 6 | 10 | 11.60 | (Да) |
responseType = 'arraybuffer' |
10 | 6 | 10 | 11.60 | (Да) |
responseType = 'blob' |
19 | 6 | 10 | 12 | (Да) |
responseType = 'document' |
18 | 11 | 10 | Нет | 6.1 |
responseType = 'json' |
31 | 10 | Нет | 12 (Presto) 17 (Chromium) |
(Да) |
| Progress Events | 7 | 3.5 | 10 | 12 | (Да) |
withCredentials |
3 | 3.5 | 10 | 12 | 4 |
timeout |
29 | 12.0 | 8 | 12 16 |
(Да) |
responseType = 'moz-blob' |
Нет | 12.0 | Нет | Нет | Нет |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | 0.16 | (Да) | ? | ? | ? |
Gecko notes
Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) removed support for using the responseType and withCredentials attributes when performing synchronous requests. Attempting to do so throws an NS_ERROR_DOM_INVALID_ACCESS_ERR exception. This change has been proposed to the W3C for standardization.
Gecko 12.0 (Firefox 12.0 / Thunderbird 12.0 / SeaMonkey 2.9) and later support using XMLHttpRequest to read from data: URLs.
Gecko 20.0 (Firefox 20.0 / Thunderbird 20.0 / SeaMonkey 2.17) adds the support of sending an ArrayBufferView - sending a plain ArrayBuffer is not part of the XMLHttpRequest specification any longer and should be treated as deprecated.
Opera notes
Before switching to Blink/Chromium Opera supported responseType between Opera 12 and Opera 15. Support is added again after it is implemented also in Blink (Opera 17).=json
See also
- MDN articles about XMLHttpRequest:
- XMLHttpRequest references from W3C and browser vendors:
- W3C: XMLHttpRequest (base features)
- W3C: XMLHttpRequest (latest editor's draft with extensions to the base functionality, formerly XMLHttpRequest Level 2
- Microsoft documentation
- Apple developers' reference
- "Using the XMLHttpRequest Object" (jibbering.com)
- XMLHttpRequest - REST and the Rich User Experience
- HTML5 Rocks - New Tricks in XMLHttpRequest2
- Thread on the naming convention of
XMLHttpRequest Chrome scope availability- how to access from JSM modules etc which do not have access to DOM