原生请求

JS原生发送异步请求

GET

1
2
3
4
5
6
7
8
9
10
serveGET () {
let xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 &&xhr.status == 200) {
console.log(JSON.parse(xhr.response))
}
}
xhr.open('get', 'https://api.coindesk.com/v1/bpi/currentprice.json', true)
xhr.send(null)
}

POST

1
2
3
4
5
6
7
8
9
10
serve () {
let xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.response))
}
}
xhr.open('post', 'https://api.coindesk.com/v1/bpi/currentprice.json')
xhr.send('name=xixi&id=123')
}

fetch

1
2
3
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))