首页 > 解决方案 > 如何在 Vanilla Javascriot 的 Unsplash Api 中使用分页

问题描述

我正在尝试用狗的照片(Unsplash API)制作一个具有无限滚动功能的网站。但是当我在滚动事件上调用 getphotos() 函数时,它只会给我第一页上的图像。

我试图通过制作 3 个不同的 getphotos() 函数并通过属性页号传递不同的 apiURL 来解决这个问题。改变了。它确实有效,但我认为这不是最好的方法。我浏览了文档,但似乎没有任何效果。我想在滚动事件中调用 getphotos() 函数,并且每次它应该从不同的页面返回图像。

const apiUrl = `https://api.unsplash.com/search/photos/?page=1&query=dogs&client_id=${apiKey}&per_page=${per_page}&order_by=relevant;` 

const apiUrl2 = `https://api.unsplash.com/search/photos/?page=2&query=dogs&client_id=${apiKey}&per_page=${per_page}&order_by=relevant;`

const apiUrl3 = `https://api.unsplash.com/search/photos/?page=3&query=dogs&client_id=${apiKey}&per_page=${per_page}&order_by=relevant;` 



 async function getPhotos(){
    try{
        const response = await fetch(apiUrl);
        photosArray = await response.json();
        console.log(photosArray);
        displayPhotos();
    }catch(error){
        console.log(error);
    }
}

async function getPhotos2(){
    try{
        const response = await fetch(apiUrl2);
        photosArray = await response.json();
        displayPhotos();
        getPhotos3();
    }catch(error){
        console.log(error);
    }
}

async function getPhotos3(){
    try{
        const response = await fetch(apiUrl3);
        photosArray = await response.json();
        displayPhotos();
    }catch(error){
        console.log(error);
    }
}

标签: javascriptarraysapiasync-awaitdom-events

解决方案


推荐阅读