AJAX - Đối tượng XMLHttpRequest
Nền tảng của AJAX là đối tượng XMLHttpRequest.
- Tạo một đối tượng XMLHttpRequest
- Xác định 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ợ đối tượng XMLHttpRequest
.
Đối tượng XMLHttpRequest
có thể được sử dụng để trao đổi dữ liệu với máy chủ web ở 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ó đối tượng XMLHttpRequest
tích hợp sẵn.
Cú pháp tạo đối tượng XMLHttpRequest
:
variable = new XMLHttpRequest();
Xác định hàm 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 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 các phương thức open() và send() của đối tượng XMLHttpRequest
:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Ví 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();
Hãy tự mình thử »Truy cập trên các tên 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 nhiều miền.
Điều này có nghĩa là cả trang web và tệp XML mà nó cố tải phải được đặt trên cùng một máy chủ.
Các ví dụ trên Example.com.vn đều là 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 thì 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 received (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 đối tượng XMLHttpRequest
bạn có thể xác định 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 này được định nghĩa trong thuộc tính onload
của đối tượng XMLHttpRequest
:
Ví dụ
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Hãy tự mình thử »Nhiều chức năng gọi lại
Nếu bạn có nhiều tác vụ AJAX trong một trang web, bạn nên tạo một hàm để thực thi đối tượng XMLHttpRequest
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.
Ví 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 tính readyState
giữ trạng thái của XMLHttpRequest.
Thuộc tính onreadystatechange
xác định hàm gọi lại sẽ được thực thi khi trạng thái sẵn sàng thay đổi.
Thuộc tính status
và thuộc tính statusText
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 trạng thái sẵn sàng thay đổi.
Khi readyState
là 4 và trạng thái là 200, phản hồi đã sẵn sàng:
Ví 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();
}
Hãy tự mình thử » Sự kiện onreadystatechange
được kích hoạt bốn lần (1-4), một lần cho mỗi thay đổi ở trạng thái sẵn sàng.