http://jsonplaceholder.typicode.com/posts
測試代碼用到的是谷歌瀏覽器
一古涧、使用axios請求這個測試接口(完整代碼)垂券,現(xiàn)在流行的也是使用這個方法。
圖片中的注釋又臭又長主要是面對初學(xué)者羡滑,嫌麻煩的可以直接復(fù)制代碼自己運行下一目了然圆米。
(代碼沒有問題,如果請求不到可以檢查看有沒有單詞寫錯地方)
這是axios文檔地址https://www.kancloud.cn/yunye/axios/234845
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
</body>
<script>
let url = 'http://jsonplaceholder.typicode.com/posts'
let test = axios({
method: 'get',
url: url,
})
test.then(res => {
console.log(res)
})
</script>
</html>
axios方法解析
個人理解:axios使用es6新增的promise方法對→異步請求數(shù)據(jù)XMLHttpRequest對象的再封裝
因為是這樣我們才能使用axios來異步請求數(shù)據(jù)啄栓,并且可以使用.then這個方法來處理獲取到的數(shù)據(jù)娄帖。
二、使用XMLHttpRequest請求這個測試接口(完整代碼)昙楚。
參考文檔地址https://www.runoob.com/ajax/ajax-xmlhttprequest-onreadystatechange.html
補充:test.send( )是指發(fā)送這個請求近速。
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
let url = 'http://jsonplaceholder.typicode.com/posts'
let test = new XMLHttpRequest();
test.open("GET",url,true)
test.send()
test.onreadystatechange = () =>{
if(test.readyState === 4 && test.status === 200){
console.log(test.responseText)
}
}
</script>
</html>
XMLHttpRequest方法解析
三、使用fetch請求這個測試接口,(fetch同樣也是es新增方法削葱,不需要安裝插件)
參考文檔https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
let url = 'http://jsonplaceholder.typicode.com/posts'
let test = fetch(url)
test.then(res => res.json())
.then(res => console.log(res))
</script>
</html>
使用json( )方法
未使用json( )方法