XMLHttpRequest、fetch的ajax请求

// XMLHttpRequest请求
function xhr (url, data) {
    var xhr = new XMLHttpRequest()
    if (xhr) {
        xhr.open('POST', url, true) // 默认为异步true、同步为false
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(data) // 需要传递的参数
       xhr.onreadystatechange = function() {
            // 0:未初始化。尚未调用open()方法。
            // 1:启动。已经调用open()方法,但尚未调用send()方法。
            // 2:发送。已经调用send()方法,但尚未接收到响应。
            // 3:接收。已经接收到部分响应数据。
            // 4:完成。已经接收到全部响应数据,而且已经可以在客户端使用了。
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
        }
    }
}
xhr('https://www.baidu.com', {})

// fetch请求
function fth (url, data) {
    fetch(url, {
        method: 'POST', // 请求方法GET、POST、PUT、DELETE、HEAD
        body: data, // 提交的数据
        mode: 'cors', // 跨域设置cors、no-cors、same-origin
        redirect: "follow", // 重定向设置follow、error、manual
        headers: {'Accept': 'application/json'},
        cache: 'default' // 缓存模式default、reload,、no-cache
    }).then(function(res) { 
        return res // 使用return后可以链式书写
    }).then(function(res) {
        console.log(res)
    }).catch(function (err) {
        console.log(err)
    })
}
fth('https://www.baidu.com', {})

  

posted @ 2018-06-20 23:57  鱿鱼须须  阅读(215)  评论(0编辑  收藏  举报