前端原生js请求后台接口

封装请求

function httpRequest(obj, successfun, errFun) {
    var xmlHttp = null;
    //创建 XMLHttpRequest 对象,老版本的 Internet Explorer (IE5 和 IE6)
    //使用 ActiveX 对象:xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    if (window.XMLHttpRequest) {
        //code for all new browsers
        xmlHttp = new XMLHttpRequest;
    } else if (window.ActiveXObject) {
        //code for IE5 and IE6
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //判断是否支持请求
    if (xmlHttp == null) {
        alert("浏览器不支持xmlHttp");
        return;
    }
    //请求方式, 转换为大写
    var httpMethod = (obj.method || "Get").toUpperCase();
    //数据类型
    var httpDataType = obj.dataType || 'json';
    //url
    var httpUrl = obj.url || '';
    //异步请求
    var async = true;
    //post请求时参数处理
    if (httpMethod == "POST") {
        requestData = JSON.stringify(obj.data)
        console.log(requestData);
    }
    //onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,
    //当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。
    //状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码
    xmlHttp.onreadystatechange = function () {
        //complete
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                //请求成功执行的回调函数
                successfun(xmlHttp.responseText);
            } else {
                //请求失败的回调函数
                errFun;
            }
        }
    }
    //请求接口
    if (httpMethod == 'GET') {
        xmlHttp.open("GET", httpUrl, async);
        xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xmlHttp.send(null);
    } else if (httpMethod == "POST") {
        xmlHttp.open("POST", httpUrl, async);
        xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xmlHttp.send(requestData);
    }
}

执行请求

httpRequest({
        method: "post",
        url: "https://jstest.91betterwei.com/burypoint-api/save", //请求的url地址
        data: {
            applicationId: "1",
            type: "1", // type  1 直接点击  2 通过分享点击
        },
        dataType: "json"
    }, function (res) {
        console.log(res)
    }, function () {
        console.log("请求失败");
    });
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值