【问题标题】:How To Set Fetch Data In to Array Using JavaScipt And Set Data In To innerHTML Boostrap card如何使用 JavaScript 将获取数据设置为数组并将数据设置为 innerHTML 引导卡
【发布时间】:2021-07-19 22:25:44
【问题描述】:

我有这样的获取方法。

async function sendApiRequest() {
    let APP_ID = "f61bb958";
    let APP_Key = "7c465e19d8e2cb3bc8f79e7a6e18961e"
    let INPUT_VALUE = document.getElementById("inputRecipe").value;
    console.log(INPUT_VALUE)
    fetch(`https://api.edamam.com/search?app_id=${APP_ID}&app_key=${APP_Key}&q=${INPUT_VALUE}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            document.getElementById("ripeCard").innerHTML = `
       <div class="card" style="width: 18rem;">
           <img src="${data.image}" class="card-img-top" alt="...">
          <div class="card-body">
          <h5 class="card-title">Card title</h5>
           <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>         
      </div>
            `
        })
}

API返回数据如下:

count: 7000
from: 0
hits: Array(10)
0:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_1b6dfeaf0988f96b187c7c9bb69a14fa", label: "Pizza Dough", image: "https://www.edamam.com/web-img/284/2849b3eb3b46aa0e682572d48f86d487.jpg", source: "Lottie + Doof", url: "http://www.lottieanddoof.com/2010/01/pizza-pulp-fiction-jim-lahey/", …}
__proto__: Object
1:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_0209cb28fc05320434e2916988f47b71", label: "White Pizza", image: "https://www.edamam.com/web-img/dfe/dfe2e44c86334a3a3a5f774dda576121.jpg", source: "Food52", url: "https://food52.com/recipes/40095-white-pizza", …}
__proto__: Object
2:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_77db6e25dffe1836d4407cf4575f0141", label: "Chorizo, caper & rocket pizza", image: "https://www.edamam.com/web-img/7fe/7fee72cbf470edc0089493eb663a7a09.jpg", source: "BBC Good Food", url: "http://www.bbcgoodfood.com/recipes/1506638/chorizo-caper-and-rocket-pizza", …}
__proto__: Object
3:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_c9bf37296a0126d18781c952dc45a230", label: "Pizza Frizza recipes", image: "https://www.edamam.com/web-img/94a/94aeb549b29ac92dced2ac55765f38f9", source: "Martha Stewart", url: "http://www.marthastewart.com/284463/pizza-frizza", …}
__proto__: Object
4:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_b2ebad01df2a319d259c2d3f61eb40c5", label: "Margarita Pizza With Fresh Mozzarella & Basil", image: "https://www.edamam.com/web-img/d72/d72d1b7dd988e3b340a4b90ed3d56603.jpg", source: "Big Girls Small Kitchen", url: "http://www.biggirlssmallkitchen.com/2010/06/cooking-for-others-bff-pizza-party.html", …}
__proto__: Object
5:
recipe: {uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_1b25671a32284038b57ad8b49c44af68", label: "Grilled BLT Pizza recipes", image: "https://www.edamam.com/web-img/2ac/2ac98d88117ff8f2327d302ab290b164", source: "Food Republic", url: "http://www.foodrepublic.com/recipes/grilled-blt-pizza-recipe/", …}
__proto__: Object
6: {recipe: {…}}
7: {recipe: {…}}
8: {recipe: {…}}
9: {recipe: {…}}
length: 10
__proto__: Array(0)
more: true
q: "pizza"
to: 10

我需要将 Fetch Data 设置为 innerHTML Boostrap 卡。 但要做到这一点,我需要将获取数据设置为数组。 如何将我的 Fetch Data 设置为数组以及如何将 Fetch Data 设置为 innerHTML Boostrap 卡..?

谢谢你..!

【问题讨论】:

    标签: javascript html ajax api fetch


    【解决方案1】:

    我认为您需要从 API 获得的是配方,因此 API 在 hits 属性中返回它们。 hits 属性是一个食谱数组

    配方对象中的属性是;所以你可以选择你需要的,

    ['uri', 'label', 'image', 'source', 'url', 'shareAs', 'yield', 'dietLabels', 'healthLabels', 'cautions', 'ingredientLines', 'ingredients', 'calories', 'totalWeight', 'totalTime', 'cuisineType', 'mealType', 'dishType', 'totalNutrients', 'totalDaily', 'digest'];
    

    async function sendApiRequest() {
        let APP_ID = 'f61bb958';
        let APP_Key = '7c465e19d8e2cb3bc8f79e7a6e18961e';
        let INPUT_VALUE = document.getElementById('inputRecipe').value;
        const response = await fetch(`https://api.edamam.com/search?app_id=${APP_ID}&app_key=${APP_Key}&q=${INPUT_VALUE}`);
        const data = await response.json();
    
        document.getElementById('ripeCard').innerHTML = ''; // Resetting the content of the element
    
        // Iterating through the array of recipes and destructuring the result object to give only the recipe property
        data.hits.forEach(({recipe}) => {
            document.getElementById('ripeCard').innerHTML += `
           <div class="card" style="width: 18rem;">
               <img src="${recipe.image}" class="card-img-top" alt="...">
              <div class="card-body">
              <h5 class="card-title">${recipe.label}</h5>
               <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            <a href="${recipe.url}" class="btn btn-primary">Go somewhere</a>         
          </div>`;
        });
    }
    
    sendApiRequest();
    <input id="inputRecipe" value="pizza">
    <div id="ripeCard"></div>

    【讨论】:

    • 非常感谢您,先生..!
    【解决方案2】:

    您应该将每个任务分解为一个单独的函数。此外,搜索输入的去抖动函数包装器将使搜索更有效。我借用Josh W Comeau网站sn-p的去抖功能。

    无论如何,您的 API 数据包含一个名为 hits 的密钥。这包含一个对象数组,带有一个名为recipe 的键。该对象保存的值包括labelcaloriesingredients 等信息。您要显示哪些数据取决于您。

    注意:数据显示为分页,下面的示例不支持分页。这将由您来实施。

    const API_URL = 'https://api.edamam.com';
    const APP_ID = "f61bb958";
    const APP_KEY = "7c465e19d8e2cb3bc8f79e7a6e18961e"
    
    const cards = document.querySelector('#recipe-cards');
    
    const main = async() => {
      const searchInput = document.querySelector('#input-recipe');
      searchInput.addEventListener('input', searchRecipes);
      triggerEvent(searchInput, 'input');
    };
    
    const cardAsHtml = ({ recipe }) => `
      <div class="card" style="width: 18rem;">
        <img src="${recipe.image}" class="card-img-top" alt="..." />
        <div class="card-body">
          <h5 class="card-title">${recipe.label} (${recipe.calories.toFixed(0)} cals)</h5>
          <p class="card-text"><ul>${recipe.ingredientLines.map(line =>
            `<li>${line}</li>`).join('')}</ul></p>
          <a href="#" class="btn btn-primary">Go somewhere</a>    
        </div>
      </div>
    `;
    
    // https://www.joshwcomeau.com/snippets/javascript/debounce/
    const debounce = (callback, wait) => {
      let timeoutId = null;
      return (...args) => {
        window.clearTimeout(timeoutId);
        timeoutId = window.setTimeout(() => {
          callback.apply(null, args);
        }, wait);
      };
    };
    
    const updateRecipes = (data) => {
      cards.innerHTML = '';
      data.hits.forEach(hit => cards.insertAdjacentHTML('beforeend', cardAsHtml(hit)));
    };
    
    const searchRecipes = debounce((ev) => {
      const query = document.getElementById('input-recipe').value;
      sendApiRequest(API_URL, APP_ID, APP_KEY, query)
        .then(updateRecipes)
    }, 250);
    
    const sendApiRequest = async(url, id, key, query) => {
      const response = await fetch(`${url}/search?app_id=${id}&app_key=${key}&q=${query}`);
      return response.json();
    };
    
    // http://youmightnotneedjquery.com/#trigger_custom
    const triggerEvent = (el, eventName, data = {}) => {
      let event;
      if (window.CustomEvent && typeof window.CustomEvent === 'function') {
        event = new CustomEvent(eventName, {detail: data});
      } else {
        event = document.createEvent('CustomEvent');
        event.initCustomEvent(eventName, true, true, data);
      }
      el.dispatchEvent(event);
    };
    
    main();
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
    <label>Search: <input type="text" id="input-recipe" value="cake" placeholder="Cake, pie, etc."/></label>
    <div id="recipe-cards"></div>

    【讨论】:

    • 非常感谢您,先生..!
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2014-07-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    相关资源
    最近更新 更多