Rumah  >  Artikel  >  hujung hadapan web  >  如何实现AJAX请求?

如何实现AJAX请求?

Guanhui
Guanhuiasal
2020-06-24 15:31:052688semak imbas

如何实现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教程

Atas ialah kandungan terperinci 如何实现AJAX请求?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn