美文网首页
原生js AJAX

原生js AJAX

作者: z1900 | 来源:发表于2017-11-09 15:44 被阅读0次

原生

function getlist(url) {
    let xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }

    xhr.open('GET', url, true);
    xhr.setRequestHeader('token', token);

    xhr.onreadystatechange = function() {
        if (this.readyState !== 4) {
            return;
        }
        if (this.status === 200) {
            let data = JSON.parse(this.response);
            console.log(data.msg)
        } else {
            console.log(this.statusText)
        }
    }
        
        xhr.send()
}
getList(host+'/ftk/users?page_no=0&page_size=10') 

封装

const ajax = {
    get: function(url, token_key, fn) {
        let xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Mecrosoft.XMLHTTP');
        }

        xhr.open('GET', host+url, true);
        xhr.setRequestHeader('token', token_key);
        xhr.onreadystatechange = function() {
            let self = this
            if (this.readyState ===4 && this.status === 200) {
                fn.call(self, this.responseText);
            }
        }
        xhr.send()
    }
}

function getList(msg) {
    // console.log(msg)
    let data = JSON.parse(this.response);
    console.log(data)
}

ajax.get('/ftk/users?page_no=0&page_size=10', token, getList)

promise

const Ajax = {
    post: function(url, data,token) {
        let promise = new Promise((resolve, reject) => {
            let xhr;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject('Microsoft.XMLHTTP', true);
            }
            xhr.open('POST' ,host+url, true);
            xhr.responseType = 'json';
            xhr.setRequestHeader('token', token);
            // xhr.setRequestHeader('Content-Type', 'application/json');
                        // post请求的请求头必须是这个,否则参数无法解析
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                console.log(this)
                if (this.readyState === 4 && this.status === 200) {
                    resolve(this.response);
                } else {
                    // reject(this.statusText);
                }
            }
            xhr.send(data)
        })
        return promise;
    }
}

Ajax.post('/ftk/users/user/login', 'user_id=13333333333&user_passwd=123', token)
.then(res => {
    console.log(res)
})
.catch(e => console.log(e))

相关文章

网友评论

      本文标题:原生js AJAX

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