XMLHttpRequest、fetch的ajax请求
生活随笔
收集整理的這篇文章主要介紹了
XMLHttpRequest、fetch的ajax请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// XMLHttpRequest請求
function xhr (url, data) {var xhr = new XMLHttpRequest()if (xhr) {xhr.open('POST', url, true) // 默認為異步true、同步為falsexhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')xhr.send(data) // 需要傳遞的參數xhr.onreadystatechange = function() {// 0:未初始化。尚未調用open()方法。// 1:啟動。已經調用open()方法,但尚未調用send()方法。// 2:發(fā)送。已經調用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、HEADbody: data, // 提交的數據mode: 'cors', // 跨域設置cors、no-cors、same-originredirect: "follow", // 重定向設置follow、error、manualheaders: {'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', {})
轉載于:https://www.cnblogs.com/huangtonghui/p/9206741.html
總結
以上是生活随笔為你收集整理的XMLHttpRequest、fetch的ajax请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TCP/IP 学习 --- 2
- 下一篇: dede标签用法(来源网页)