AJAX - Đối tượng XMLHttpRequest
Keystone của AJAX là đối tượng XMLHttpRequest.
- Tạo một đối tượng XMLHttpRequest
- Xác định một hàm gọi lại
- Mở đối tượng XMLHttpRequest
- Gửi yêu cầu đến máy chủ
Đối tượng XMLHttpRequest
Tất cả các trình duyệt hiện đại đều hỗ trợ XMLHttpRequest
đối tượng.
Đối XMLHttpRequest
tượng có thể được sử dụng để trao đổi dữ liệu với một máy chủ web phía sau hậu trường. Điều này có nghĩa là 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.
Tạo một đối tượng XMLHttpRequest
Tất cả các trình duyệt hiện đại (Chrome, Firefox, IE, Edge, Safari, Opera) đều có một XMLHttpRequest
đối tượng tích hợp sẵn.
Cú pháp để tạo một XMLHttpRequest
đối tượng:
variable = new XMLHttpRequest();
Xác định một chức năng gọi lại
Hàm gọi lại là một hàm được truyền dưới dạng tham số cho một hàm khác.
Trong trường hợp này, hàm gọi lại phải chứa mã để thực thi khi phản hồi sẵn sàng.
xhttp.onload = function() {
// What to do when the response is ready
}
Gửi yêu cầu
Để gửi yêu cầu đến máy chủ, bạn có thể sử dụng phương thức open () và send () của
XMLHttpRequest
đối tượng:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Thí dụ
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
// Here you can use the Data
}
// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Truy cập trên các miền
Vì lý do bảo mật, các trình duyệt hiện đại không cho phép truy cập trên các miền.
Điều này có nghĩa là cả trang web và tệp XML mà nó cố gắng tải, phải được đặt trên cùng một máy chủ.
Các ví dụ trên W3Schools tất cả các tệp XML mở nằm trên miền W3Schools.
Nếu bạn muốn sử dụng ví dụ trên trên một trong các trang web của riêng mình, các tệp XML bạn tải phải được đặt trên máy chủ của riêng bạn.
Các phương thức đối tượng 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 |
Thuộc tính đối tượng XMLHttpRequest
Property | Description |
---|---|
onload | Defines a function to be called when the request is recieved (loaded) |
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") |
Thuộc tính onload
Với XMLHttpRequest
đối tượng, bạn có thể xác định một hàm gọi lại sẽ được thực thi khi yêu cầu nhận được câu trả lời.
Hàm được định nghĩa trong thuộc onload
tính của XMLHttpRequest
đối tượng:
Thí dụ
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Nhiều chức năng gọi lại
Nếu bạn có nhiều hơn một tác vụ AJAX trong một trang web, bạn nên tạo một hàm để thực thi XMLHttpRequest
đối tượng và một hàm gọi lại cho mỗi tác vụ AJAX.
Lệnh gọi hàm phải chứa URL và hàm nào sẽ gọi khi phản hồi sẵn sàng.
Thí dụ
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Thuộc tính onreadystatechange
Thuộc readyState
tính giữ trạng thái của XMLHttpRequest.
Thuộc onreadystatechange
tính xác định một hàm gọi lại sẽ được thực thi khi readyState thay đổi.
Thuộc status
tính và các statusText
thuộc tính giữ trạng thái của đối tượng 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 |
status | 200: "OK" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
Hàm onreadystatechange
được gọi mỗi khi readyState thay đổi.
Khi readyState
là 4 và trạng thái là 200, phản hồi đã sẵn sàng:
Thí dụ
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
Sự onreadystatechange
kiện được kích hoạt bốn lần (1-4), một lần cho mỗi thay đổi trong Trạng thái sẵn sàng.