XML HttpTalebi
Tüm modern tarayıcılarda, bir sunucudan veri istemek için yerleşik bir XMLHttpRequest nesnesi bulunur.
XMLHttpRequest Nesnesi
XMLHttpRequest nesnesi, bir web sunucusundan veri istemek için kullanılabilir.
XMLHttpRequest nesnesi bir geliştiricinin hayalidir çünkü şunları yapabilirsiniz:
- Sayfayı yeniden yüklemeden bir web sayfasını güncelleyin
- Bir sunucudan veri iste - sayfa yüklendikten sonra
- Bir sunucudan veri alın - sayfa yüklendikten sonra
- Bir sunucuya veri gönder - arka planda
XMLHttpRequest Örneği
Aşağıdaki giriş alanına bir karakter yazdığınızda, sunucuya bir XMLHttpRequest gönderilir ve bazı ad önerileri (sunucudan) döndürülür:
Örnek
Yukarıdaki örnek, bu öğreticinin AJAX bölümlerinde açıklanmıştır.
XMLHttpRequest Gönderme
XMLHttpRequest nesnesini kullanmak için yaygın bir JavaScript sözdizimi şuna benzer:
Örnek
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
Örnek Açıklama
Yukarıdaki örnekteki ilk satır bir XMLHttpRequest nesnesi oluşturur:
var xhttp = new XMLHttpRequest();
onreadystatechange özelliği, XMLHttpRequest nesnesinin durumu her değiştiğinde yürütülecek bir işlevi belirtir:
xhttp.onreadystatechange = function()
ReadyState özelliği 4 ve status özelliği 200 olduğunda , yanıt hazırdır:
if (this.readyState == 4 && this.status == 200)
ResponseText özelliği , sunucu yanıtını bir metin dizesi olarak döndürür.
Metin dizesi bir web sayfasını güncellemek için kullanılabilir:
document.getElementById("demo").innerHTML = xhttp.responseText;
Bu öğreticinin AJAX bölümlerinde XMLHttpRequest nesnesi hakkında çok daha fazlasını öğreneceksiniz.
Internet Explorer'ın Eski Sürümleri (IE5 ve IE6)
Internet Explorer'ın eski sürümleri (IE5 ve IE6), XMLHttpRequest nesnesini desteklemez.
IE5 ve IE6'yı işlemek için tarayıcının XMLHttpRequest nesnesini destekleyip desteklemediğini kontrol edin veya bir ActiveXObject oluşturun:
Örnek
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}