朋友们,美好的一天!开发Web应用程序时,通常有必要从服务器获取数据。如今,有很多方法可以在JavaScript中执行此操作。让我们看看在实践中如何使用XMLHttpRequest,Fetch和Axios。这些任务将使用JSONPlaceholder-伪造的在线REST API,用于测试和原型制作(换句话说,是培训数据库)。XMLHttpRequest
任务:获取用户列表并在控制台中显示此列表。决定:
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users')
xhr.send()
xhr.onload = () => xhr.status != 200 ? console.error(xhr.status) : console.table(JSON.parse(xhr.response))
xhr.onprogress = event => {
if (event.lengthComputable) {
console.dir(`received ${event.loaded} of ${event.total} bytes`)
} else {
console.dir(`received ${event.loaded} bytes`)
}
}
xhr.onerror = () => console.error('error')
结果:GitHub上的
代码。取
任务:类似。解决方案(与XMLHttpRequest比较):fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => console.table(json))
.catch(error => console.error(error))
结果:GitHub上的
代码。
或者,如果您喜欢异步/等待更多:(async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users')
const data = await response.json()
console.table(data)
} catch (error) {
console.error(error)
} finally {
console.log('done')
}
})()
结果:GitHub上的
代码。
让我们使任务复杂一些:现在,您需要从服务器获取图像并从它们中形成图库。
决定:const url = 'https://jsonplaceholder.typicode.com/photos/'
getPhotosAndMakeGallery(url)
function getPhotosAndMakeGallery(url) {
for (let i = 1; i < 11; i++) {
fetch(url + i)
.then(response => response.json())
.then(photo => {
let img = document.createElement('img')
img.src = photo.url
document.body.append(img)
})
}
}
结果:GitHub上的
代码。Axios
要连接此库,您需要在文档的开头添加<script src =“ unpkg.com/axios/dist/axios.min.js ”> </ script>。任务:获取用户列表并将其显示在控制台中。决定:axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => console.table(response.data))
.catch(error => console.log(error))
GitHub的
代码。或者,如果您希望异步/等待:(async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
console.table(response.data);
} catch (error) {
console.error(error);
}
})()
GitHub的
代码。我们使任务复杂化:获取待办事项并创建列表。决定:const url = 'https://jsonplaceholder.typicode.com/todos/'
getTodosAndMakeList()
function getTodosAndMakeList() {
const ul = document.createElement('ul')
document.body.append(ul)
for (let i = 1; i < 21; i++) {
axios.get(url + i)
.then(response => {
let li = document.createElement('li')
li.textContent = `title: ${response.data.title}; completed: ${response.data.completed}`
ul.append(li)
})
.catch(error => console.log(error))
}
}
结果:GitHub上的
代码。
我们使之复杂化:获取用户,评论和照片,合并这些数据并以可读形式呈现所有内容。
决定:function getUsers(i) {
return axios.get('https://jsonplaceholder.typicode.com/users/' + i)
}
function getComments(i) {
return axios.get('https://jsonplaceholder.typicode.com/comments/' + i)
}
function getPhotos(i) {
return axios.get('https://jsonplaceholder.typicode.com/photos/' + i)
}
(async() => {
for (let i = 1; i < 7; i++) {
let request = await axios.all([getUsers(i), getComments(i), getPhotos(i)])
.then(axios.spread(function(user, comment, photo) {
let figure = document.createElement('figure')
document.body.append(figure)
let figcaption = document.createElement('figcaption')
figcaption.textContent = `Post ${i}`
figure.append(figcaption)
let img = document.createElement('img')
img.src = photo.data.url
figure.append(img)
let userName = document.createElement('p')
userName.innerHTML = `<span>Name:</span> ${user.data.username}`
figure.append(userName)
let userComment = document.createElement('p')
userComment.innerHTML = `<span>Comment:</span> ${comment.data.body}`
figure.append(userComment)
}))
}
})()
结果:GitHub上的
代码。
感谢您的关注。