ajax

1、创建一个httprequest对象

var xhr = new XMLHttpRequest();

2、打开http请求

  - get  请求方式  get/posh

  - data.txt  请求地址

  - false 是否异步,true/false 、默认为true异步

xhr.open('get','data.txt',false);

3、监听状态改变,完成数据的获取

  //onreadystatechange:  存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。  

xhr.onreadystatechange = function(){

  readyState: 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

  • 0: 请求未初始化
  • 1: 服务器连接已建立
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已就绪

  status: 200: "OK"/404: 未找到页面

  if(xhr.readyState === 4 && xhr.status === 200){

    var result = xhr.responseText;

    console.log(result); 

  }

4、发送ajax请求

xhr.send(null);

}

posted on 2019-04-08 15:14  瑾然  阅读(91)  评论(0编辑  收藏  举报

导航