JS—简单实现jquery中的ajax请求

ajax的出现直接推进了从以往的混合模式开发往前后端分离开发的转型,下面简单实现以下jquery中的ajax请求,加深对ajax的理解与运用。主要就$.ajax()、$.get()、$.post()作简单,使用立即执行函数,函数中返回对象作一个模块。

  /**
     *使用举例:
      ajax请求:
      xhr.ajax({
            url:"http://localhost:3002/api",
            type:"POST",
            data:{
                state:1,
            },
            success: data => {
                console.log(data);
            },
            error: err => {
                console.log(err);
            },
            complete: _ => {

            }
        })
      get请求
      xhr.get("http://localhost:3002/api",data=>{console.log(data)})

      post请求:
      xhr.post("http://localhost:3002/api",{state:1}, data=>{console.log(data)})
     */

    var xhr = (function(){
        function _doAjax(opt){
            // 获取数据
            var type = (opt.type || "GET").toUpperCase(),
                url = opt.url,
                async = opt.async || true, // 默认为异步
                data = opt.data || null, //GET请求的数据为null
                success = opt.success || function(){},
                error = opt.error || function(){},
                complete = opt.complete || function(){};

            // 创建XMLHttpRequest对象
            var o = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            if(!url){
                throw new Error("你没有填写URL");
            }else{
                o.open(type, url, async); 
                if(type==="POST"){
                    // 设置请求头部的信息
                    o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    data && (data = _formateData(data)); 
                }
                o.send(data); //发出请求
                o.onreadystatechange = function(){
                    if(o.readyState === 4 && o.status === 200){
                        success(JSON.parse(o.responseText));
                    }
                    if(o.status === 404){
                        error();
                    }

                    complete();
                }
            }
        }

        // POST请求时将请求的对象数据data转换成&连接
        function _formateData(data) {
            var res = '';
            for(var key in data){
                res += key + "=" + data[key]+'&';
            }
            return res.replace(/&$/, '');
        }

        return {
            ajax(opt){
                _doAjax(opt);
            },
            get(url,cb){
                _doAjax({
                    url,
                    success: cb,
                });
            },
            post(url, data, cb){
                _doAjax({
                    type:"POST",
                    url,
                    data,
                    success: cb,
                });
            }
        }
    })(); //立即执行函数,函数可作模块对象。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值