首頁  >  文章  >  web前端  >  如何實現AJAX請求?

如何實現AJAX請求?

Guanhui
Guanhui原創
2020-06-24 15:31:052686瀏覽

如何實現AJAX請求?

如何實作AJAX請求?

1、建立XMLHttpRequest實例;

var xhr;if(window.XMLHttpRequest) {
  //ie7+,firefox,chrome,safari,opera
  xhr = new XMLHttpRequest();}else {
  //ie5,ie6
  xhr = new ActiveXObject("Microsoft.XMLHTTP");}

2、監聽readystatechange事件,並透過readyState屬性來判斷請求狀態;

xhr.onreadystatechange = function() {
  if(xhr.readyState==4 && xhr.status==200) {
    console.log(xhr.responseText);
  }}

3、呼叫open()方法指定請求類型和位址;

xhr.open("GET", "xhr_info.txt");

4、呼叫send()方法傳送請求即可。

xhr.send(null);

完整程式碼

var xhr;
if(window.XMLHttpRequest) {
  //ie7+,firefox,chrome,safari,opera
  xhr = new XMLHttpRequest();
} else {
  //ie5,ie6
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
  if(xhr.readyState==4 && xhr.status==200) {
    console.log(xhr.responseText);
  }
}
xhr.open("GET", "xhr_info.txt", true);
xhr.send(null);

推薦教學:《JS教學

以上是如何實現AJAX請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn