网络——ajax请求数据过程解析,封装ajax函数;

ajax(Asynchronous Javascript And XML),异步js和xml(json);

  • 可以在不刷新网页的情况下向服务器发送数据(请求数据);
  • 异步更新,不重新加载数据;(form表单终结者)

创建ajax对象;

var xhr = null;
    if(XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHttp');
    }

初始化ajax对象,根据数据请求方式post/get,选择数据传输方式;

若为post,需要手动规定传输数据的各式,通常两种编码方式,data 不编码,和urlencoded;

发起数据请求;

    if(way == 'POST'){
        xhr.open(way,url,flag);
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xhr.send(data);
    }else{
        xhr.open(way,url + '?' + data,flag);
        xhr.send();
    }

根据onreadystate判断数据接收状态;

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

onreadystatechange 监控readyState变化;

整体函数:


    function ajax(way,data,url,flag,callBack) {
        var xhr = null;
        if(XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject('Microsoft.XMLHttp');
        }
        way = way.toUpperCase();
        if(way == 'POST'){
            xhr.open(way,url,flag);
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            xhr.send(data);
        }else{
            xhr.open(way,url + '?' + data,flag);
            xhr.send();
        }
        xhr.onreadystatechange = function () {
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    callBack(xhr.responseText);
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_41265663/article/details/82780530