美文网首页
项目 ajax封装

项目 ajax封装

作者: 一只章鱼哥 | 来源:发表于2021-01-29 15:43 被阅读0次
Ajax的基本封装
function ajax(ops){
// 先处理默认属性
ops.type = ops.type || "get";
ops.data = ops.data || "";
// 根据当前的请求方式,决定是否需要拼接数据,处理url
ops.url = ops.type=="get" ? ops.url + "?" + ops.data : ops.url;
var xhr = new XMLHttpRequest();
// 打开请求
xhr.open(ops.type, ops.url);
// 根据类型决定send的内容及内容数据格式
if(ops.type == "get"){
    xhr.send();
}else{
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send(ops.data);
}
// 开启监听
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status === 200){
        // 执行回调函数,取出数据
        ops.success(xhr.responseText);
    }
}
}
//调用代码
document.onclick = function(){
//url根据具体地址修改
    var url = "http://localhost/ajax/data/get-post.php";
    ajax({
    //成功后执行
        success:function(res){
        console.log(res);
        },
        url:url,
        type:"get",
        data:"user=admin&pass=123"
    });
}

相关文章

网友评论

      本文标题:项目 ajax封装

      本文链接:https://www.haomeiwen.com/subject/kevxtltx.html