封装AJAX

function Ajax(obj) {
    let xmlhttp = '';
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open(obj.type, obj.url, true);
    xmlhttp.setRequestHeader('content-type', 'application/json');
    let param = '' || JSON.stringify(obj.param)
    xmlhttp.send(param);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            let data = JSON.parse(xmlhttp.responseText)
            obj.success(data)
        }
    }
}
let ajax = Ajax
ajax({
    type: 'POST',
    url: 'http://xxx',
    param: {
        name: 'zhangsan',
        password: '1234'
    },
    success: function(res) {
        console.log(res)
    }
})

  

posted @ 2021-06-21 15:53  不要香菜谢谢~  阅读(21)  评论(0编辑  收藏  举报
123456