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

JS条件模态框:API返回空结果时触发无结果提示弹窗

API返回空结果时触发模态框的逻辑修复

问题原因

原有代码将模态框弹出逻辑直接绑定在搜索按钮点击事件上,没有和API返回结果的判断逻辑关联,导致点击按钮就直接弹窗,不符合预期。

修复后完整代码

HTML部分(原有结构无需改动,仅替换提示文本为中文即可)

<div class="modal" id="myModal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>未找到结果</p>
  </div>
</div>
<button class="btn" id="searchBtn">Search</button>

整合后的JS逻辑(含API调用、弹窗触发、弹窗关闭能力)

// 初始化DOM节点引用
var modal = document.getElementById("myModal");
var btn = document.getElementById("searchBtn");
var span = document.getElementsByClassName("close")[0];

// 搜索按钮点击事件:发起API请求
btn.onclick = function(){
  var newRecipe = 
    'https://api.spoonacular.com/recipes/findByIngredients?ingredients='+ 
    allIngreds + '&number=10&apiKey=39791063581a4d96a908bb19745b3f64';

  fetch(newRecipe)
  .then(response => {
    if (!response.ok){
      throw Error("ERROR")
    };
    return response.json();
  })
  .then(data => {
    console.log(data);
    // 仅当返回结果为长度0的数组时,弹出模态框
    if (Array.isArray(data) && data.length === 0) {
      modal.style.display = "block";
    }
    // 此处可追加有匹配结果时的列表渲染逻辑
  })
  .catch(err => {
    console.log('请求错误', err)
  })
};

// 点击关闭按钮隐藏弹窗
span.onclick = function(){
  modal.style.display = "none";
};

// 点击遮罩层隐藏弹窗
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
};

核心修改点

  • 移除了按钮点击事件中直接弹出模态框的错误逻辑
  • 将原本独立的API调用逻辑移入搜索按钮点击回调中,点击按钮才会发起请求
  • 在API请求成功的回调中增加结果判断:仅当返回值是数组、且数组长度为0时才触发弹窗
  • 补全了原有JS代码缺失的语法闭合括号
  • 完整保留原有弹窗关闭能力:点击关闭按钮、点击模态框遮罩区域均可正常关闭弹窗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:09:11