Ajax学习

对Ajax的理解?

是基于XHR(XMLHttpRequest)实现的

HTML:Hyper Text Markup Language

XML:Extensible Markup Language(在html之上能够拓展的语言)

比如:不局限于Html:

<parent>
   <son></son>
   <son></son>
</parent>

Ajax:asynchronous javascript and XML(异步的js和xml)

实现局部刷新技术,利用js单独向服务器发送http请求。

所有基于ajax的通讯,基本都是json的数据格式

实现方式

1.创建xhr对象

var xhr;
if(window.XMLHttpRequest){
  xhr=new XMLHttpRequest(); // ie7+
}else {
  xhr= new ActiveXObject('Microsoft.HMLHTTP');
}

2.发送http(Hyper Text Transfer Protocol)请求

发送请求之前要建立连接
xhr.open(‘get',url,false); // 用来指定请求的方式,请求的url,同步还是异步(true)请求

xhr.send();
// 有4个主要的属性
// responseText:文本
// responseXML:xml;'application/xml','text/xml’
// status:
// statusText:

if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
  console.log(xhr.responseText);
}

-------------------------------------------------------------------
异步:
xhr.open(‘get',url,true);
xhr.send();

// xhr.readyState
// 0代表初始化,什么都没做
// 1代表启动
// 2代表发送
// 3是浏览器接收
// 4完成

xhr.onreadystatechange=()=>{
   if(xhr.readyState === 4){
      if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
           console.log(xhr.responseText);
      }
   }
}

3.前端接收服务器返回的结果

4.处理服务器给的结果,渲染

var $ = () => {
    function _doAjax(opt) {
        var o = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Mocrosoft.XMLHTTP");
        if (!o) {
            throw new Error("您的浏览器不支持异步发起http请求");
        }
        var opt = opt || {},
            type = (opt.type || 'GET').toUpperCase(),
            async = "" + opt.async === 'false',
            dataType = opt.dataType || 'JSON',
            jsonp = opt.jsonp || 'cb',
            jsonpCallback = opt.jsonpCallback || 'jQuery' + randomNum() + '_' + new Date().getTime();
        (url = opt.url),
            (data = opt.data || null),
            (timeout = opt.timeout || 30000),
            (error = opt.error || function () { }),
            (success = opt.success || function () { }),
            (complete = opt.complete || function () { }),
            (t = null);

        if (!url) {
            throw new Error('您没有填写url')
        }

        if (dataType.toUpperCase() === 'JSONP' && type !== 'GET') {
            throw new Error('如果dataType为JSONP,type请您设置GET或不设置');
        }

        if (dataType.toUpperCase() === 'JSONP') {
            var oScript = document.createElement('script');
            oScript.src =
                url.indexOf('?') === -1 ?
                    url + "?" + jsonp + '=' + jsonpCallback :
                    url + '&' + jsonp + '=' + jsonpCallback;
            document.body.appendChild(oScript);
            document.body.removeChild(oScript);
            window[jsonpCallback] = function (data) {
                success(data);
            };
            return;
        }

        o.onreadystatechange = () => {
            if (o.readyState === 4) {
                if ((o.status >= 200 && o.status < 300) || o.status === 304) {
                    switch (dataType.toUpperCase()) {
                        case 'JSON':
                            success(JSON.parse(o.responseText));
                            break;
                        case 'TEXT':
                            success(o.responseText);
                            break;
                        case 'XML':
                            success(o.responseXML);
                            break;
                        default:
                            success(JSON.parse(o.responseText));
                    }
                } else {
                    error();
                }
                complete();
                clearTimeout(t);
                t = null;
                o = null;
            }
        };

        o.open(type, url, async);
        type === 'POST' &&
            o.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        o.send(type === 'GET' ? null : formatDatas(data));
        t = setTimeout(() => {
            o.abort();
            clearTimeout();
            t = null;
            o = null;
            throw new Error('本次请求已超时' + url);
        }, timeout);
    }
}

function formatDatas(obj) {
    var str = '';
    for (var key in obj) {
        str += key + '=' + obj[key] + '&';
    }
    return str.replace(/&$/, '');
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值