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

如何使用AJAX从指定URL接口获取JSON数据并在浏览器展示

代码调整方案

你原有代码存在三处问题:

  • 回调函数内误用了未定义的$response变量,应直接使用回调接收的response参数
  • 没有从返回的JSON结构中提取volcano字段对应的火山数组
  • 缺少将数据渲染到#data页面容器的逻辑

修正后的完整代码如下:

var settings = {
  "url": "http://localhost:1337/api/volcano",
  "method": "GET",
  "timeout": 0,
  // 显式指定返回数据类型为JSON,避免解析异常
  "dataType": "json"
};

$.ajax(settings).done(function (response) {
  // 提取火山数组
  var volcanoArr = response.volcano;
  var renderHtml = '';
  // 遍历数组拼接展示HTML
  volcanoArr.forEach(function(volcanoItem) {
    renderHtml += `
      <div class="volcano-card">
        <h4>${volcanoItem.Name}</h4>
        <p>ID:${volcanoItem.id}</p>
        <p>所属区域:${volcanoItem.Location}</p>
        <p>历史记录:${volcanoItem.History}</p>
        <p>活跃状态:${volcanoItem.Active}</p>
      </div>
      <hr>
    `;
  });
  // 将内容插入到页面容器
  $('#data').html(renderHtml);
}).fail(function(err) {
  // 请求异常时的提示
  $('#data').html('数据加载失败,请检查本地1337服务是否正常启动');
  console.error('请求错误信息:', err);
});

注意事项

  • 需确保本地http://localhost:1337服务正常运行,接口路径正确
  • 如果出现跨域报错,需要在1337服务端配置CORS跨域访问规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:06:05