// XMLHttpRequest請求
function xhr (url, data) {
var xhr = new XMLHttpRequest()
if (xhr) {
xhr.open('POST', url, true) // 默認(rèn)為異步true、同步為false
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(data) // 需要傳遞的參數(shù)
xhr.onreadystatechange = function() {
// 0:未初始化。尚未調(diào)用open()方法。
// 1:啟動(dòng)。已經(jīng)調(diào)用open()方法,但尚未調(diào)用send()方法。
// 2:發(fā)送。已經(jīng)調(diào)用send()方法,但尚未接收到響應(yīng)。
// 3:接收。已經(jīng)接收到部分響應(yīng)數(shù)據(jù)。
// 4:完成。已經(jīng)接收到全部響應(yīng)數(shù)據(jù),而且已經(jīng)可以在客戶端使用了。
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, // 提交的數(shù)據(jù)
mode: 'cors', // 跨域設(shè)置cors、no-cors、same-origin
redirect: "follow", // 重定向設(shè)置follow、error、manual
headers: {'Accept': 'application/json'},
cache: 'default' // 緩存模式default、reload,、no-cache
}).then(function(res) {
return res // 使用return后可以鏈?zhǔn)綍鴮? }).then(function(res) {
console.log(res)
}).catch(function (err) {
console.log(err)
})
}
fth('https://www.baidu.com', {})