AJAX - XMLHttpRequest Nesnesi
AJAX'ın temel taşı, XMLHttpRequest nesnesidir.
- Bir XMLHttpRequest nesnesi oluşturun
- Bir geri arama işlevi tanımlayın
- XMLHttpRequest nesnesini açın
- Sunucuya İstek Gönder
XMLHttpRequest Nesnesi
Tüm modern tarayıcılar XMLHttpRequest
nesneyi destekler.
Nesne XMLHttpRequest
, perde arkasında bir web sunucusuyla veri alışverişi yapmak için kullanılabilir. Bu, tüm sayfayı yeniden yüklemeden bir web sayfasının bölümlerini güncellemenin mümkün olduğu anlamına gelir.
Bir XMLHttpRequest Nesnesi Oluşturun
Tüm modern tarayıcıların (Chrome, Firefox, IE, Edge, Safari, Opera) yerleşik bir XMLHttpRequest
nesnesi vardır.
XMLHttpRequest
Bir nesne oluşturmak için sözdizimi :
variable = new XMLHttpRequest();
Bir Geri Arama İşlevi Tanımlayın
Geri arama işlevi, başka bir işleve parametre olarak geçirilen bir işlevdir.
Bu durumda, geri arama işlevi, yanıt hazır olduğunda yürütülecek kodu içermelidir.
xhttp.onload = function() {
// What to do when the response is ready
}
İstek gönder
Bir sunucuya istek göndermek için
XMLHttpRequest
nesnenin open() ve send() yöntemlerini kullanabilirsiniz:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Örnek
// 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();
Etki Alanları Arasında Erişim
Güvenlik nedeniyle, modern tarayıcılar etki alanları arasında erişime izin vermez.
Bu, hem web sayfasının hem de yüklemeye çalıştığı XML dosyasının aynı sunucuda bulunması gerektiği anlamına gelir.
W3Schools'daki örnekler, W3Schools etki alanında bulunan tüm açık XML dosyalarıdır.
Yukarıdaki örneği kendi web sayfalarınızdan birinde kullanmak istiyorsanız yüklediğiniz XML dosyalarının kendi sunucunuzda bulunması gerekir.
XMLHttpRequest Nesne Yöntemleri
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 Nesne Özellikleri
Property | Description |
---|---|
onload | Defines a function to be called when the request is recieved (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") |
onload Özelliği
Nesne ile XMLHttpRequest
, istek bir yanıt aldığında yürütülecek bir geri arama işlevi tanımlayabilirsiniz.
İşlev, nesnenin onload
özelliğinde tanımlanır:XMLHttpRequest
Örnek
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Çoklu Geri Çağırma İşlevleri
Bir web sitesinde birden fazla AJAX göreviniz varsa, XMLHttpRequest
nesneyi yürütmek için bir işlev ve her AJAX görevi için bir geri çağırma işlevi oluşturmalısınız.
İşlev çağrısı, URL'yi ve yanıt hazır olduğunda hangi işlevin çağrılacağını içermelidir.
Örnek
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
}
onreadystatechange Özelliği
Özellik readyState
, XMLHttpRequest durumunu tutar.
Özellik onreadystatechange
, readyState değiştiğinde yürütülecek bir geri arama işlevi tanımlar.
Özellik status
ve statusText
özellikler, XMLHttpRequest nesnesinin durumunu tutar.
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") |
onreadystatechange
ReadyState her değiştiğinde işlev çağrılır .
readyState
4 ve durum 200 olduğunda yanıt hazırdır :
Örnek
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();
}
Olay onreadystatechange
, readyState'deki her değişiklik için bir kez olmak üzere dört kez (1-4) tetiklenir.