首页 > 解决方案 > 将动态id插入api请求链接显示数据

问题描述

我的代码有问题,找不到将我拥有的食谱的 ID 插入新请求以将食谱的卡路里显示到 HTML 中的解决方案。我想要的只是以某种方式在 API url 中添加一个动态 id 而不是静态 634091 id,因为如果我发送该请求并刷新我的页面,它将不会在 HTML 中显示卡路里,因为它将是从每个生成的另一个 id刷新。如果不清楚,我可以提供更多信息,非常感谢您抽出宝贵时间。

js:

setTimeout(function () {
  const api_url_calories =
    "https://api.spoonacular.com/recipes/634091/nutritionWidget.json";

  // Defining async function
  async function getapi(url) {
    // Storing response
    const response = await fetch(url);

    // Storing data in form of JSON
    var data = await response.json();
    console.log(data);
    data.calories.forEach((obj) => {
      /*
        create new DOM elements
    */
      let div = document.createElement("div");
      let calories = document.createElement("p");

      div.append(calories);

      /*
        assign content from api data
    */

      calories.innerHTML = obj.calories;

      /*
        add to DOM
    */
      displayRecipes.append(div);
    });

    //   if (response) {
    //     console.log("data here");
    //   }
  }

  getapi(api_url_calories);
}, 100);

HTML:

<body>
    <div id="displayRecipes"></div>
</body>

来自 api 对卡路里信息的响应是这样的:

{
    "calories": "316",
    "carbs": "49g",
    "fat": "12g",
    "protein": "3g",
    "bad": [
        {
            "name": "Calories",
            "amount": "316",
            "indented": false,
            "percentOfDailyNeeds": 15.84
        },

来自 id 来自的食谱请求的 js

const api_url =
  "https://api.spoonacular.com/recipes/random?number=3";

// Defining async function
async function getapi(url) {
  // Storing response
  const response = await fetch(url);

  // Storing data in form of JSON
  var data = await response.json();
  console.log(data);
  data.recipes.forEach((obj) => {
    /*
        create new DOM elements
    */
    let div = document.createElement("div");
    let h1 = document.createElement("h1");
    let image = new Image();
    let cuisines = document.createElement("p");
    let id = document.createElement("p");

    div.append(h1);
    div.append(image);
    div.append(cuisines);
    div.append(id);

    /*
        assign content from api data
    */
    h1.innerHTML = obj.title;
    image.src = obj.image;
    for (let i = 0; i < 100; i++) {
      cuisines.innerHTML = obj.cuisines;
    }
    // cuisines.innerHTML = obj.cuisines[0];
    id.innerHTML = obj.id;

    /*
        add to DOM
    */
    displayRecipes.append(div);
  });
  //   if (response) {
  //     console.log("data here");
  //   }
}
// Calling that async function
getapi(api_url);

食谱数据的外观如何,它有一个 id 键。

"recipes": [
        {
            "vegetarian": false,
            "vegan": false,
            "glutenFree": false,
            "dairyFree": false,
            "veryHealthy": false,
            "cheap": false,
            "veryPopular": false,
            "sustainable": false,
            "weightWatcherSmartPoints": 1,
            "gaps": "no",
            "lowFodmap": false,
            "aggregateLikes": 11,
            "spoonacularScore": 21.0,
            "healthScore": 1.0,
            "creditsText": "Foodista.com – The Cooking Encyclopedia Everyone Can Edit",
            "license": "CC BY 3.0",
            "sourceName": "Foodista",
            "pricePerServing": 12.65,
            "extendedIngredients": [
                {
                    "id": 1123,
                    "aisle": "Milk, Eggs, Other Dairy",
                    "image": "egg.png",
                    "consistency": "solid",
                    "name": "eggs",
                    "nameClean": "egg",
                    "original": "3 eggs, slightly beaten",
                    "originalString": "3 eggs, slightly beaten",
                    "originalName": "eggs, slightly beaten",
                    "amount": 3.0,
                    "unit": "",
                    "meta": [
                        "slightly beaten"
                    ],
                    "metaInformation": [
                        "slightly beaten"
                    ],
                    "measures": {
                        "us": {
                            "amount": 3.0,
                            "unitShort": "",
                            "unitLong": ""
                        },
                        "metric": {
                            "amount": 3.0,
                            "unitShort": "",
                            "unitLong": ""
                        }
                    }
                },

标签: javascripthtml

解决方案


您可以通过串联实现此目的:

const recipe_id = "YOUR_DESIRED_ID";
const api_url_calories =
    "https://api.spoonacular.com/recipes/" + recipe_id + "/nutritionWidget.json";

推荐阅读