【问题标题】:Load Data from Json file从 Json 文件加载数据
【发布时间】:2022-01-09 04:56:46
【问题描述】:

请在此代码中帮助我 我是 UI 设计师,对代码一无所知 我有 Json 文件有数据以 id 1 到 id 25 开头, 我使用 id 和 math.random() 加载此数据代码工作但我的问题相同的 id 显示两次或两次以上我只需要显示 25 个 id 唯一 例如结果是 (2, 4, 18, 14, 7, 13, 13, 4) 但我不希望同一个 id 显示多个 并且当 25 个 id 显示它们都停止功能时

json文件的后端代码

const express = require('express');
const app = express();
const importData = require("./data.json");
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/posts', (req, res) => {
    res.send(importData);
});

app.get('/posts/:id', (req, res) => {
  const post = importData.find(c => c.id === parseInt(req.params.id));
  if (!post) res.status(404).send("Error");
  res.send(post);
});

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});


app.listen(port, () => {
  console.log(`Example app listening at ${port}`);
});

前端js文件

const container = document.getElementById('container'); const loading = document.querySelector('.loading');

// this load 4 posts
getPost();
getPost();
getPost();
getPost();

window.addEventListener('scroll', () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

    console.log( { scrollTop, scrollHeight, clientHeight });
    
    if(clientHeight + scrollTop >= scrollHeight - 5) {
        // show the loading animation
        showLoading();
    }
});

function showLoading() {
    loading.classList.add('show');
    
    // load more data
    setTimeout(getPost, 300)
}

async function getPost() {
    // the orginal url have (25) id in the json file
    // tips this is fake url i can't post the orginal url because it will my server
    const postResponse = await fetch(`https://example.com/posts/${getRandomNr()}`);
    const postData = await postResponse.json();
    
    const data = { post: postData};
    
    addDataToDOM(data);

    console.log(data);
}

function getRandomNr() {
    return Math.floor(Math.random() * 25) + 1;
}

function addDataToDOM(data) {
    const postElement = document.createElement('div');
    postElement.classList.add('blog-post');
    postElement.innerHTML = `
        <h2 class="title">${data.post.title}</h2>
        <p class="text">${data.post.body}</p>
        <div class="user-info">
            <img src="${data.post.src}" alt="${data.post.title}" />
            <span>${data.post.title}</span>
        </div>
    `;
    container.appendChild(postElement);
    
    loading.classList.remove('show');
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container" id="container">
        <h1>Blog Posts</h1>
    <!--    <div class="blog-post">
            <h2 class="title">Blog post title</h2>
            <p class="text">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
            <div class="user-info">
                <img src="https://randomuser.me/api/portraits/women/26.jpg" alt="pic" />
                <span>Leah Taylor</span>
            </div>
        </div> -->
    </div>
    
    <div class="loading">
        <div class="ball"></div>
        <div class="ball"></div>
        <div class="ball"></div>
    </div>    
    <script src="script.js"></script>
</body>
</html>

【问题讨论】:

    标签: javascript json api


    【解决方案1】:

    您可以使用函数和数组来处理不重复的相同数字,如下所示。您可以将数字数组放在实现的顶部。

    这不是明智的做法。你说你是 UI 设计师。所以,我实现了可以理解的方式,而不是更聪明的方式。

    
    var numbers = [
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 20, 21, 22,
      23, 24, 25,
    ];
    
    function getRandomNr() {
      var x = Math.floor(Math.random() * numbers.length);
      const temp = numbers[x];
    
      // find index of random value in numbers
      // and delete it to not repeat number again
      var index = numbers.indexOf(temp);
      if (index > -1) {
        numbers.splice(index, 1);
        return temp;
      } else {
        // if code goes here that means
        // we got all 25 numbers between 1 and 25
        // and the numbers array is empty
        // so we can return -1 or anything we want
        return -1;
      }
    }
    
    

    【讨论】:

    • 抱歉,同一个 id 仍然不止一个
    • 不可能多次产生同一个id。我认为您的后端服务器实现可能是错误的。
    • 我编辑了问题并添加了后端文件,请把它放到海里告诉我是什么问题
    • 其实后端看的不错。你能和我分享一下你是如何将我的实现添加到你的代码中的吗?
    【解决方案2】:

    尝试类似var array = Object.values(myobject) 这样的操作会将对象自身的所有可枚举属性值保存在一个数组中。然后你想洗牌阵列。您可以使用此代码执行此操作。 var shuffledArray = array.sort((a, b) =&gt; 0.5 - Math.random()); 最后,您将拥有一个数组,其中包含对象的所有值以随机顺序排列。

    【讨论】:

    • 能否请您在编辑时输入脚本,因为我没有任何编码经验
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    确实,您的问题的解决方案是创建一个项目列表,然后对其进行迭代。

    除了上述方法之外,另一种方法是生成四个不同的数字,然后使用您的代码对它们实际做一些有用的事情。

    function showLoading() {
        loading.classList.add('show');
        const rnd = new Set();
        do {
            rnd.add(getRandomNr());
        } while (rnd.size < 4);
        // load more data
        setTimeout(()=>rnd.forEach(nr => getPost(nr), 300));
    }
    async function getPost(id) { 
        const postResponse = await fetch(`https://example.com/posts/${id}`);
    ......
    }
    

    只是为了澄清: 集合是项目的列表,其中每个项目只能存在一次。因此,在您的情况下,如果已经添加了一个数字,则不会再次添加它,从而为您留下不同的项目。

    完整的代码应该是这样的:

    const container = document.getElementById('container');
    const loading = document.querySelector('.loading');
    
    window.addEventListener('scroll', () => {
      const {
        scrollTop,
        scrollHeight,
        clientHeight
      } = document.documentElement;
    
      console.log({
        scrollTop,
        scrollHeight,
        clientHeight
      });
    
      if (clientHeight + scrollTop >= scrollHeight - 5) {
        showLoading();
        // show the loading animation
      }
    });
    
    function showLoading() {
      loading.classList.add('show');
      const rnd = new Set();
      do {
        rnd.add(getRandomNr());
        console.log(88)
      } while (rnd.size < 4);
      // load more data
      console.log(rnd)
      setTimeout(() => rnd.forEach(nr => getPost(nr), 300));
    }
    async function getPost(id) {
      const postResponse = await fetch(`https://example.com/posts/${id}`);
      const postData = await postResponse.json();
      const data = {
        post: postData
      };
    
      addDataToDOM(data);
    }
    
    function getRandomNr() {
      return Math.floor(Math.random() * 25) + 1;
    }
    
    function addDataToDOM(data) {
      const postElement = document.createElement('div');
      postElement.classList.add('blog-post');
      postElement.innerHTML = `
            <h2 class="title">${data.post.title}</h2>
            <p class="text">${data.post.body}</p>
            <div class="user-info">
                <img src="${data.post.src}" alt="${data.post.title}" />
                <span>${data.post.title}</span>
            </div>
        `;
      container.appendChild(postElement);
    
      loading.classList.remove('show');
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body>
      <div class="container" id="container">
        <h1>Blog Posts</h1>
        <!--    <div class="blog-post">
                <h2 class="title">Blog post title</h2>
                <p class="text">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
                <div class="user-info">
                    <img src="https://randomuser.me/api/portraits/women/26.jpg" alt="pic" />
                    <span>Leah Taylor</span>
                </div>
            </div> -->
      </div>
    
      <div class="loading">
        <div class="ball"></div>
        <div class="ball"></div>
        <div class="ball"></div>
      </div>
      <script src="script.js"></script>
    </body>
    
    </html>

    【讨论】:

    • 对不起,但仍然发布多个相同的 id,请您在编辑时输入脚本,因为我没有任何编码经验
    • 编辑了答案。
    • 我真的对你很害羞,但是当我使用此代码时不起作用,当我删除参数 id 并用 getRandomNr() 替换 ${id} 时,就像之前一样显示相同的 id 不止一个也许来自服务器json文件的问题我用express创建它并在其中使用此代码 app.get('/posts/:id', (req, res) => { const post = importData.find(c => c .id === parseInt(req.params.id)); if (!post) res.status(404).send("Error"); res.send(post); });
    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 2018-05-11
    • 2020-02-28
    • 2012-02-28
    • 2013-08-28
    • 2012-06-10
    • 2017-06-01
    • 2016-04-14
    相关资源
    最近更新 更多