iT邦幫忙

2026 iThome 鐵人賽

0
自我挑戰組

AI Recipe — AI 智慧食譜推薦系統系列 第 16 篇

把AI 回傳結果顯示到網頁

  • 分享至 

  • xImage
  •  

前幾天已經讓 AI 能夠根據食材產生料理建議,也開始使用 JSON 格式整理資料。

今天要把這些資料真正放進網站介面中,讓使用者不需要閱讀一大段文字,就能清楚看到食譜資訊。

一、解析 AI 回傳的 JSON

假設 AI 回傳的內容是一段 JSON 文字,可以使用 JSON.parse() 將它轉換成 JavaScript 物件。

const recipe = JSON.parse(jsonText);

console.log(recipe.name);
console.log(recipe.ingredients);
console.log(recipe.steps);

二、建立食譜顯示函式

在 script.js 中建立:

function displayRecipe(recipe) {
    recipeResult.replaceChildren();

    const card = document.createElement("div");
    card.className = "recipe-card";

    const title = document.createElement("h2");
    title.textContent = recipe.name;

    const time = document.createElement("p");
    time.textContent = `料理時間:${recipe.time} 分鐘`;

    const difficulty = document.createElement("p");
    difficulty.textContent = `難度:${recipe.difficulty}`;

    const ingredients = document.createElement("p");
    ingredients.textContent =
        `所需食材:${recipe.ingredients.join("、")}`;

    const steps = document.createElement("p");
    steps.textContent =
        recipe.steps.join("\n");

    card.append(title, time, difficulty, ingredients, steps);
    recipeResult.appendChild(card);
}

三、今天的成果

現在網站可以將食譜資料分別顯示,不再只是呈現一大段 AI 回答。

實際串接時,還要確認後端回傳的資料格式與前端預期一致;如果 AI 回傳的 JSON 不正確,也要避免直接解析而造成程式中斷。

今天完成了 AI 結果與網頁介面的初步整合,下一篇要加入載入畫面,改善等待 AI 回答時的使用體驗。


上一篇
讓 AI回傳固定格式
下一篇
Loading! AI思考時不要讓使用者乾等
系列文
AI Recipe — AI 智慧食譜推薦系統 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言