AJAX - كائن XMLHttpRequest
حجر الأساس في AJAX هو كائن XMLHttpRequest.
كائن XMLHttpRequest
تدعم جميع المتصفحات الحديثة كائن XMLHttpRequest.
يمكن استخدام كائن XMLHttpRequest لتبادل البيانات مع خادم خلف الكواليس. هذا يعني أنه من الممكن تحديث أجزاء من صفحة الويب دون إعادة تحميل الصفحة بأكملها.
قم بإنشاء كائن XMLHttpRequest
تحتوي جميع المتصفحات الحديثة (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
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") |