Đối tượng XMLHttpRequest
Với đối tượng XMLHttpRequest, bạn có thể cập nhật các phần của trang web mà không cần tải lại toàn bộ trang.
Hãy tự mình thử - Ví dụ
Tạo một XMLHttpRequest đơn giản và truy xuất dữ liệu từ tệp TXT.
Truy xuất thông tin tiêu đề của một tài nguyên (tệp).
Truy xuất thông tin tiêu đề cụ thể của một tài nguyên (tệp).
Cách một trang web có thể giao tiếp với máy chủ web trong khi người dùng nhập ký tự vào trường nhập.
Cách một trang web có thể tìm nạp thông tin từ cơ sở dữ liệu với đối tượng XMLHttpRequest.
Tạo một XMLHttpRequest để truy xuất dữ liệu từ tệp XML và hiển thị dữ liệu trong bảng HTML.
Đối tượng XMLHttpRequest
Đối tượng XMLHttpRequest được sử dụng để trao đổi dữ liệu với máy chủ phía sau hậu trường.
Đối tượng XMLHttpRequest là niềm mơ ước của các nhà phát triển , bởi vì bạn có thể:
- Cập nhật trang web mà không cần tải lại trang
- Yêu cầu dữ liệu từ máy chủ sau khi trang đã tải xong
- Nhận dữ liệu từ máy chủ sau khi trang đã tải xong
- Gửi dữ liệu đến máy chủ trong nền
Các phương thức đối tượng XMLHttpRequest
Method | Description |
---|---|
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method,url,async,uname,pswd) | Specifies the type of request, the URL, if the request should be handled asynchronously or not, and other optional attributes of a request
method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) |
send(string) | send(string) Sends the request off to the server. string: Only used for POST requests |
setRequestHeader() | Adds a label/value pair to the header to be sent |
Thuộc tính đối tượng XMLHttpRequest
Property | Description |
---|---|
onreadystatechange | Stores a function (or the name of a function) to be called automatically each time the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. Changes from 0 to 4: 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 (e.g. "404" for "Not Found" or "200" for "OK") |
statusText | Returns the status-text (e.g. "Not Found" or "OK") |