AJAX - Objek XMLHttpRequest
Keystone AJAX adalah objek XMLHttpRequest.
Objek XMLHttpRequest
Semua browser modern mendukung objek XMLHttpRequest.
Objek XMLHttpRequest dapat digunakan untuk bertukar data dengan server di belakang layar. Ini berarti dimungkinkan untuk memperbarui bagian halaman web, tanpa memuat ulang seluruh halaman.
Buat Objek XMLHttpRequest
Semua browser modern (Chrome, Firefox, Edge (dan IE7+), Safari, Opera) memiliki objek XMLHttpRequest bawaan.
Sintaks untuk membuat objek XMLHttpRequest:
variable = new XMLHttpRequest();
Contoh
var xhttp = new XMLHttpRequest();
File "ajax_info.txt" yang digunakan dalam contoh di atas, adalah file teks sederhana dan terlihat seperti ini:
<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>
Akses Lintas Domain
Untuk alasan keamanan, browser modern tidak mengizinkan akses lintas domain.
Ini berarti bahwa halaman web dan file XML yang coba dimuat, harus berada di server yang sama.
Contoh di W3Schools semua file XML terbuka yang terletak di domain W3Schools.
Jika Anda ingin menggunakan contoh di atas pada salah satu halaman web Anda sendiri, file XML yang Anda muat harus berada di server Anda sendiri.
Metode Objek 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 |
Properti Objek 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") |