javaScript系列---【原生js中的Ajax封装函数】


 // get请求
        ajax({
            type: 'get',
            url: 'http://edu.xqb.ink/api/courselist',
            data: 'limits=5',
            success: function (res) {
                console.log(res);//res回应数据
            }
        });
 // post请求
        ajax({
            type: 'post',
            url: 'http://edu.xqb.ink/api/registers',
            data: 'usr=www123321&pwd=www1234567',
            success: function (res) {
                console.log(res);
            }
        });




  // 封装ajax
  // req是参数,格式json   ex:{type: 'get', url: '请求路径', data: '参数', success: 回调函数}
  function ajax(req) {
    // 第一步:创建请求对象
    var xhr = new XMLHttpRequest();
  //第二步:配置信息(需要判断请求方式是get还是post)
    if (req.type.toLowerCase() == 'get') { // get请求
        // 如果有参数把参数拼接在url上
        req.url = req.data ? req.url + '?' + req.data : req.url;
        //get请求配置信息
        xhr.open('get', req.url, true);

     // 第三步:发送请求
        xhr.send();
    } else { // post请求
        // post请求配置信息
        xhr.open('post', req.url, true);
        // post请求需要在发送请求前设置请求头, 设置编码方式
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        // 3.发送 post请求的参数写在send方法中
        req.data ? xhr.send(req.data) : xhr.send();
    }

    // 第四步:监听事件
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                // console.log(typeof xhr.responseText);
                // document.write(xhr.responseText);
                req.success(xhr.responseText);
            }
        }
    }
}





原文地址:https://www.cnblogs.com/chenhaiyun/p/14594849.html