【问题标题】:How to load more Product Cards from JSON with a nextPage attribute如何使用 nextPage 属性从 JSON 加载更多产品卡
【发布时间】:2021-09-26 12:21:32
【问题描述】:

我在相互嵌套 fetch 时遇到问题。我实际上不知道这是否是 fetch 的工作原理,但我的意图是让 Vanilla JavaScript 从 JSON 列表中的 nextPage url 加载另一个 JSON,当我按下“加载更多”按钮时,加载更多产品。 json一共有8个产品,我想每次按下按钮加载4个。

我目前可以从第一个 JSON 加载 8 个产品,但是当我尝试加载 nextPage 时出现错误。是否有正确的方法来加载 nextPage 并使用其数据?

到目前为止我的代码:

"use strict"

var formatter = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
  });

fetch("http://frontend-intern-challenge-api.iurykrieger.now.sh/products?page=1")
.then(function(resp) {
    return resp.json();
})

.then(function(data) {
    var products = data.products;
    var i = 0;
    if (matchMedia('only screen and (max-width: 1000px)').matches) {
        for(i; i < 4; i++){
        let card = document.createElement('div');
        card.className = "product_card";
        card.innerHTML = `
        <img src="${products[i].image}" alt="Card de Produto">
        <div class="card_content">
            <h3>${products[i].name}</h3>
            <p>${products[i].description}</p>
            <p>De: ${formatter.format(products[i].oldPrice)}</p>
            <h4>Por: ${formatter.format(products[i].price)}</h4>
            <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
            <button type="button" class="btn_compra">Comprar</button>
        </div>
        `
        document.getElementById('product-container').appendChild(card);
        }
        document.getElementById('button-more').addEventListener('click', () => {
            if(i == 4) {
                for(i; i < 8; i++){
                    let card = document.createElement('div');
                    card.className = "product_card";
                    card.innerHTML = `
                    <img src="${products[i].image}" alt="Card de Produto">
                    <div class="card_content">
                        <h3>${products[i].name}</h3>
                        <p>${products[i].description}</p>
                        <p>De: ${formatter.format(products[i].oldPrice)}</p>
                        <h4>Por: ${formatter.format(products[i].price)}</h4>
                        <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                        <button type="button" class="btn_compra">Comprar</button>
                        </div>
                    `
                    document.getElementById('product-container').appendChild(card);
                    }
                    i = 0;
            } else if(i == 0) {
                fetch(data.nextPage)
                .then(function(resp) {
                        return resp.json();
                    })
                .then(function(data) {
                    products = data.products;
                })
                for(i; i < 4; i++){
                    let card = document.createElement('div');
                    card.className = "product_card";
                    card.innerHTML = `
                    <img src="${products[i].image}" alt="Card de Produto">
                    <div class="card_content">
                        <h3>${products[i].name}</h3>
                        <p>${products[i].description}</p>
                        <p>De: ${formatter.format(products[i].oldPrice)}</p>
                        <h4>Por: ${formatter.format(products[i].price)}</h4>
                        <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                        <button type="button" class="btn_compra">Comprar</button>
                    </div>
                    `
                    document.getElementById('product-container').appendChild(card);
                }
            }
        })

    } else {
        for(let i = 0; i < 8; i++){
            let card = document.createElement('div');
            card.className = "product_card";
            card.innerHTML = `
            <img src="${products[i].image}" alt="Card de Produto">
            <div class="card_content">
                <h3>${products[i].name}</h3>
                <p>${products[i].description}</p>
                <p>De: ${formatter.format(products[i].oldPrice)}</p>
                <h4>Por: ${formatter.format(products[i].price)}</h4>
                <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                <button type="button" class="btn_compra">Comprar</button>
            </div>
            `
            document.getElementById('product-container').appendChild(card);
        }
    }
});

我收到此错误消息

更新 这就是我想出的:

"use strict"

var formatter = new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL',
  
    // These options are needed to round to whole numbers if that's what you want.
    //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
    //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
  });

fetch("http://frontend-intern-challenge-api.iurykrieger.now.sh/products?page=1")
.then(function(resp) {
    return resp.json();
})
.then(function(data) {
    var jsonNextPage = data.nextPage; //Store the nextPage
    var products = data.products;
    console.log(products);
    console.log(data);
    var i = 0;
    if (matchMedia('only screen and (max-width: 1000px)').matches) {
        for(i; i < 4; i++){
        let card = document.createElement('div');
        card.className = "product_card";
        card.innerHTML = `
        <img src="${products[i].image}" alt="Card de Produto">
        <div class="card_content">
            <h3>${products[i].name}</h3>
            <p>${products[i].description}</p>
            <p>De: ${formatter.format(products[i].oldPrice)}</p>
            <h4>Por: ${formatter.format(products[i].price)}</h4>
            <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
            <button type="button" class="btn_compra">Comprar</button>
        </div>
        `
        document.getElementById('product-container').appendChild(card);
        }
        document.getElementById('button-more').addEventListener('click', () => {
            if(i == 4) {
                for(i; i < 8; i++){
                    let card = document.createElement('div');
                    card.className = "product_card";
                    card.innerHTML = `
                    <img src="${products[i].image}" alt="Card de Produto">
                    <div class="card_content">
                        <h3>${products[i].name}</h3>
                        <p>${products[i].description}</p>
                        <p>De: ${formatter.format(products[i].oldPrice)}</p>
                        <h4>Por: ${formatter.format(products[i].price)}</h4>
                        <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                        <button type="button" class="btn_compra">Comprar</button>
                        </div>
                    `
                    document.getElementById('product-container').appendChild(card);
                    }
                    i = 0;
            } else if(i == 0) {
                
                fetch('http://' + jsonNextPage) //use var nextPage
                .then(function(resp) {
                        return resp.json();
                    })
                .then(function(data) {
                    jsonNextPage = data.nextPage; //immediately store the updated nextPage to the variable
                    products = data.products;
                for(i; i < 4; i++){
                    let card = document.createElement('div');
                    card.className = "product_card";
                    card.innerHTML = `
                    <img src="${products[i].image}" alt="Card de Produto">
                    <div class="card_content">
                        <h3>${products[i].name}</h3>
                        <p>${products[i].description}</p>
                        <p>De: ${formatter.format(products[i].oldPrice)}</p>
                        <h4>Por: ${formatter.format(products[i].price)}</h4>
                        <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                        <button type="button" class="btn_compra">Comprar</button>
                    </div>
                    `
                    document.getElementById('product-container').appendChild(card);
                }
            })
        }
    })

    } else {
        for(let i = 0; i < 8; i++){
            let card = document.createElement('div');
            card.className = "product_card";
            card.innerHTML = `
            <img src="${products[i].image}" alt="Card de Produto">
            <div class="card_content">
                <h3>${products[i].name}</h3>
                <p>${products[i].description}</p>
                <p>De: ${formatter.format(products[i].oldPrice)}</p>
                <h4>Por: ${formatter.format(products[i].price)}</h4>
                <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                <button type="button" class="btn_compra">Comprar</button>
            </div>
            `
            document.getElementById('product-container').appendChild(card);
        }
        
        document.getElementById('button-more').addEventListener('click', () => {
            fetch('http://' + jsonNextPage) //Same as before
            .then(function(resp) {
                return resp.json();
            })
            .then(function(data) {
                jsonNextPage = data.nextPage; //Same as before
                products = data.products;            
                for(let i = 0; i < 8; i++){
                let card = document.createElement('div');
                card.className = "product_card";
                card.innerHTML = `
                <img src="${products[i].image}" alt="Card de Produto">
                <div class="card_content">
                    <h3>${products[i].name}</h3>
                    <p>${products[i].description}</p>
                    <p>De: ${formatter.format(products[i].oldPrice)}</p>
                    <h4>Por: ${formatter.format(products[i].price)}</h4>
                    <p>ou ${products[i].installments.count}x de ${formatter.format(products[i].installments.value)}</p>
                    <button type="button" class="btn_compra">Comprar</button>
                </div>
                `
                document.getElementById('product-container').appendChild(card);
                }
            })
        })
    }
})

【问题讨论】:

  • 当你这样做时会发生什么:fetch('http://' + data.nextPage)?
  • @Daantje 我终于可以得到 nextPage 并显示第 2 页的新产品,但我必须弄清楚如何在每次新获取后不断更新数据,如何连续获取下一个页面,更新来自 fetch 的响应。
  • 将点击#button-more 的回调设为单独的函数,并在该函数的末尾调用该函数。这样它就会循环......我不想重写你的代码,因为它看起来像是你必须完成的挑战。所以你必须检查自己如何做到这一点;)
  • 这很酷,我想我知道该怎么做了,当我想出解决方案时,我会告诉你的。
  • 不知何故我使它工作:))我将编辑我的问题更新我所做的差异。但是你能解释一下在这种情况下如何使用回调函数吗?我相信它会让我的代码更干净,或者等到星期二,我的挑战是直到明天哈哈

标签: javascript html json fetch-api


【解决方案1】:

看起来nextPage 属性不包含协议。相反,它看起来像这样: frontend-intern-challenge-api.iurykrieger.now.sh/products?page=2

当您获取这样的 URL 时,您的浏览器会将其解释为相对路径,并将其附加到当前路径,在您的情况下为 localhost。获取下一页时,您需要在此处添加 http://。

fetch('http://' + data.nextPage)

【讨论】:

  • 我成功地进入了 nextPage,但我的逻辑有一些错误,因为数据只更新到第二页,而不是超过(这个 API 显然有无限的 JSON)跨度>
猜你喜欢
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2011-08-24
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多