AJAX - Đối tượng XMLHttpRequest
Nền tảng của AJAX là đối tượng XMLHttpRequest.
Đố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ủ ở 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, Edge (và IE7+), 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();
Tệp "ajax_info.txt" được sử dụng trong ví dụ trên là một tệp văn bản đơn giản và có dạng như sau:
<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>
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 |
---|---|
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") |