Ajax 封装

简单基本用法

1。实例化XMLHttpRequest()对象
2。调用open()方法读取指定文件
3。发送请求
4。绑定readystatechange事件,设置事件处理函数。
    function () {
        var xhr =  new XMLHttpRequest();
        // 输入地址
        xhr.open('get','01.txt',true);
        // 提交
        xhr.send();
        // 等待服务器返回内容
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                alert(xhr.responseText);
            }
        };
    }

兼容浏览器

var xhr;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
 }else {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }

readyState和status

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

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

status里面存储的是http状态码,根据不同的情况,服务器会返回不同的状态码。200表示成功。

GET发送数据时,

xhr.send();

POST发送数据时,

xhr.send(data);

Ajax 封装

function ajax(method, url, data, callBack) {
    // method    get/post
    // url       地址
    // data      数据
    // callBack  回调函数
    var xhr = null;
    // 创建XMLHttpRequest
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    if (method == 'get' && data) {
        url += '?' + data;
    }
    
    xhr.open(method,url,true);
    if (method == 'get') {
        xhr.send(); // get发送数据
    } else {
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); // 定义数据的类型
        xhr.send(data); // post发送数据
    }
    
    xhr.onreadystatechange = function() {
        //  readyState的值变为4,status的值为200的时候才去处理返回的数据
        if ( xhr.readyState == 4 ) {
            if ( xhr.status == 200 ) {
                // 执行回调函数,把参数传过去
                callBack && callBack(xhr.responseText);
            } else {
                alert('出错了,Err:' + xhr.status);
            }
        }
        
    }
}
原文地址:https://www.cnblogs.com/skydragonli/p/11391651.html