AJAX — объект XMLHttpRequest
Краеугольным камнем AJAX является объект XMLHttpRequest.
Объект XMLHttpRequest
Все современные браузеры поддерживают объект XMLHttpRequest.
Объект XMLHttpRequest можно использовать для обмена данными с сервером за кулисами. Это означает, что можно обновлять части веб-страницы без перезагрузки всей страницы.
Создайте объект XMLHttpRequest
Все современные браузеры (Chrome, Firefox, Edge (и IE7+), Safari, Opera) имеют встроенный объект XMLHttpRequest.
Синтаксис для создания объекта XMLHttpRequest:
variable = new XMLHttpRequest();
Пример
var xhttp = new XMLHttpRequest();
Файл «ajax_info.txt», используемый в приведенном выше примере, представляет собой простой текстовый файл и выглядит следующим образом:
<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a
technique for accessing web servers from a web page.</p>
<p>AJAX stands for
Asynchronous JavaScript And XML.</p>
Доступ через домены
Из соображений безопасности современные браузеры не разрешают доступ между доменами.
Это означает, что и веб-страница, и XML-файл, который она пытается загрузить, должны находиться на одном сервере.
В примерах W3Schools все открытые XML-файлы расположены в домене W3Schools.
Если вы хотите использовать приведенный выше пример на одной из ваших собственных веб-страниц, загружаемые файлы XML должны находиться на вашем собственном сервере.
Методы объекта XMLHttpRequest
Method | Description |
---|---|
new XMLHttpRequest() | Creates a new XMLHttpRequest object |
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method,url,async,user,psw) | Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password |
send() | Sends the request to the server Used for GET requests |
send(string) | Sends the request to the server. Used for POST requests |
setRequestHeader() | Adds a label/value pair to the header to be sent |
Свойства объекта XMLHttpRequest
Property | Description |
---|---|
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
responseText | Returns the response data as a string |
responseXML | Returns the response data as XML data |
status | Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |