You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用JS框架及后端路由,如何实现纯JS动态Recipe组件?

可以实现,无需JS框架和后端路由

完全可以用纯原生JS实现需求,核心思路是通过前端解析URL中的食谱ID,再调用API渲染详情,下面提供两种可行方案:

方案1:哈希路由(无需服务器配置,最省心)

这种方案不需要修改服务器设置,直接用URL哈希传递ID:

  • 生成列表页链接时,把原来的www.example.com/recipe/782585改为www.example.com/recipe.html#782585
  • 在recipe.html中通过原生JS提取哈希中的ID,再请求API渲染内容

核心代码示例(recipe.html)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>食谱详情</title>
</head>
<body>
  <div id="recipe-container"></div>

  <script>
    // 提取哈希中的食谱ID(去掉开头的#)
    const recipeId = window.location.hash.slice(1);
    
    // 处理无ID的情况
    if (!recipeId) {
      document.getElementById('recipe-container').innerHTML = '<p>请指定有效的食谱ID</p>';
    } else {
      fetchAndRenderRecipe(recipeId);
    }

    // 调用API并渲染详情
    async function fetchAndRenderRecipe(id) {
      try {
        const apiUrl = `https://api.spoonacular.com/recipes/${id}/information?apiKey=你的API密钥`;
        const response = await fetch(apiUrl);
        
        if (!response.ok) throw new Error('请求失败');
        const recipe = await response.json();

        // 动态生成HTML内容
        const container = document.getElementById('recipe-container');
        container.innerHTML = `
          <h1>${recipe.title}</h1>
          <img src="${recipe.image}" alt="${recipe.title}" style="max-width: 100%;">
          
          <h2>食材清单</h2>
          <ul>
            ${recipe.extendedIngredients.map(ing => `<li>${ing.original}</li>`).join('')}
          </ul>
          
          <h2>制作步骤</h2>
          ${recipe.analyzedInstructions.length > 0 ? `
            <ol>
              ${recipe.analyzedInstructions[0].steps.map(step => `<li>${step.step}</li>`).join('')}
            </ol>
          ` : '<p>暂无详细步骤说明</p>'}
        `;
      } catch (err) {
        document.getElementById('recipe-container').innerHTML = `<p>加载食谱失败:${err.message}</p>`;
        console.error(err);
      }
    }
  </script>
</body>
</html>

方案2:路径参数模式(需服务器简单配置,保留美观URL)

如果想保留www.example.com/recipe/782585这类干净的URL,需要服务器将所有/recipe/*路径的请求转发到recipe.html(这只是静态文件 fallback,不属于后端路由逻辑):

  • 服务器配置示例:
    • Nginx:在配置中添加try_files $uri $uri/ /recipe.html;
    • Apache:启用mod_rewrite,添加规则RewriteRule ^recipe/(\d+)$ /recipe.html [L]
  • 在recipe.html中通过window.location.pathname提取ID:
    const pathSegments = window.location.pathname.split('/');
    const recipeId = pathSegments[pathSegments.length - 1];
    
  • 后续的API请求和渲染逻辑和方案1一致

注意事项

  • 替换代码中的你的API密钥为实际的Spoonacular API密钥,遵守其使用条款
  • 哈希方案无需任何服务器改动,适合静态托管平台直接部署
  • 路径参数模式需要服务器配合转发,但没有后端业务逻辑,仍符合“不使用后端路由”的要求

内容的提问来源于stack exchange,提问作者Aasem Shoshari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:23:26