AJAX - XMLHttpRequest Object
คีย์สโตนของ AJAX คืออ็อบเจ็กต์ XMLHttpRequest
วัตถุ XMLHttpRequest
เบราว์เซอร์ที่ทันสมัยทั้งหมดรองรับอ็อบเจ็กต์ XMLHttpRequest
ออบเจ็กต์ XMLHttpRequest สามารถใช้ในการแลกเปลี่ยนข้อมูลกับเซิร์ฟเวอร์เบื้องหลัง ซึ่งหมายความว่าสามารถอัปเดตบางส่วนของหน้าเว็บได้โดยไม่ต้องโหลดซ้ำทั้งหน้า
สร้าง XMLHttpRequest Object
เบราว์เซอร์ที่ทันสมัยทั้งหมด (Chrome, Firefox, Edge (และ IE7+), Safari, Opera) มีวัตถุ XMLHttpRequest ในตัว
ไวยากรณ์สำหรับการสร้างวัตถุ XMLHttpRequest:
variable = new XMLHttpRequest();
ตัวอย่าง
var xhttp = new XMLHttpRequest();
ไฟล์ "ajax_info.txt" ที่ใช้ในตัวอย่างข้างต้น เป็นไฟล์ข้อความธรรมดาและมีลักษณะดังนี้:
<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>
เข้าถึงข้ามโดเมน
ด้วยเหตุผลด้านความปลอดภัย เบราว์เซอร์สมัยใหม่จึงไม่อนุญาตการเข้าถึงข้ามโดเมน
ซึ่งหมายความว่าทั้งหน้าเว็บและไฟล์ XML ที่พยายามโหลดจะต้องอยู่บนเซิร์ฟเวอร์เดียวกัน
ตัวอย่างใน W3Schools ไฟล์ XML ที่เปิดอยู่ทั้งหมดที่อยู่ในโดเมน W3Schools
หากคุณต้องการใช้ตัวอย่างด้านบนในหน้าเว็บของคุณเอง ไฟล์ XML ที่คุณโหลดจะต้องอยู่บนเซิร์ฟเวอร์ของคุณเอง
XMLHttpRequest Object Methods
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 |
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") |