ajax分装过程

ajax分装过程

一 ajax原生四步

// 创建xhrHttp实例
let xhrHttp
if(window.XMLHttpRequest){
    //创建Ajax对象 获取浏览器内部的一个XMLHttpRequest对象,创建该对象.(非IE6)
    xhrHttp= new XMLHttpRequest();
}else{
    //ie6
   xhrHttp= new ActiveXObject("Microsoft.XMLHTTP");             
}


// 监听请求和响应状态
xhrHttp.onreadyStatechange=function(){
	// 响应成功 xhrHttp.readyState 状态为4 xhrHttp.status=200
	if(xhrHttp.readyState==4 && xhrHttp.status==200){
		let responseText=xhrHttp.responseText;
		responseText=JSON.parse(responseText)
		// 进行dom操作等
		// ......
	}
}


// 与服务器创建连接
let url='http://127.0.0.1:8080/v1/rols';
let type // 'get' || 'post'
// true代表支持异步执行
xhrHttp.open(type,url,true);


// 发送请求
if(type==='post'){
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
xhrHttp.send(data) // post请求
// xhrHttp.send() // get请求

二 分装

此处分装转载 https://blog.csdn.net/qq_43806604/article/details/112876322
归纳了原创的代码

在utils文件夹下创建ajax.js
模拟jQuery方法封装

let $ = {
    ajax:function(options = {}){    //将请求的数据以对象的形式传进来
        var {type = "get",url="",data="",async=true,dataType="text",success}=options;
   		//将数据解析 默认get方法请求 默认异步操作 默认文本类型text success 回调函数
        var xhr = new XMLHttpRequest();
        if(typeof data == "object"){   //优化 如果传入的data数据是对象 那么用对象的方法将他拼接起来
            var str = "";
            for(var key in data){    //for in 方法循环遍历键名
                str += key + "=" + data[key] + "&";       //将data数据拼接起来 但最后会有一个&符号       
            }
            data = str.substring(0,str.length-1);   // 裁剪掉最后一个字符串 也就是&
        }
        
        if(type=="get"){   //如果请求的方法是get
            if(data){     //如果存在数据 那么将数据放在URL后面
                xhr.open("get",url+"?"+data,async);               
            }else{      //如果不存在数据 那么就不添加数据          
                xhr.open("get",url,async);
            }
            xhr.send();

        }else if(type=="post"){     //如果是post请求
            xhr.open("post",url,async);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   //添加这行代码
            xhr.send(data);   //将已经遍历好的数据发送
        }

        xhr.onreadystatechange = function (){
            if(xhr.readyState==4&&xhr.status==200){
                var result = xhr.responseText;
                if(dataType == "json"){    // 如果是json数据类型  将他解析
                    result = JSON.parse(xhr.responseText);
                }
                if(success){			// 如果存在回调函数 那么便执行这个回调函数
                    success(result);
                }
            }
        }    
    }
}

// type写在最后面的目的是可以省略不写 默认值是get 如果放在最前面 函数调用会调用URL当成type
export function request(url, params, type = "get") {
    return new Promise(function (resolve, reject) {
        $.ajax({
            type,
            url,
            data: {
                ...params
            },
            dataType: "json",
            success: function (result) {  // result  形式参数  表示请求成功时返回的数据
                resolve(result);
            }
        })
    })
}

在api的模块化js请求接口中引入ajax.js

import {request} from '@/utils/ajax.js'
export function login(params){
	return request("../php/login.php", params, "post");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值