溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

用javascript實(shí)現(xiàn)AJAX請(qǐng)求的方法

發(fā)布時(shí)間:2020-06-24 15:38:29 來(lái)源:億速云 閱讀:183 作者:Leah 欄目:web開(kāi)發(fā)

本篇文章展示了用javascript實(shí)現(xiàn)AJAX請(qǐng)求的具體操作,代碼簡(jiǎn)明扼要容易理解,絕對(duì)能讓你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

1、創(chuàng)建XMLHttpRequest實(shí)例;

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

2、監(jiān)聽(tīng)readystatechange事件,并通過(guò)readyState屬性來(lái)判斷請(qǐng)求狀態(tài);

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

3、調(diào)用open()方法指定請(qǐng)求類(lèi)型和地址;

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

4、調(diào)用send()方法發(fā)送請(qǐng)求即可。

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);

看完上述內(nèi)容,你們掌握用javascript實(shí)現(xiàn)AJAX請(qǐng)求的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI