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

通过HTTP请求获取JSON数据库数据并填充ul列表的实现问题

代码修正方案

你现有代码存在3个明显问题,修正后即可正常渲染列表:

  • 按钮点击事件绑定的函数名与实际定义的函数名不匹配,需要统一
  • 接口返回的JSON外层包裹了brands字段,遍历的时候需要指定遍历answer.brands
  • 缺少生成li元素并插入ul的逻辑

完整可运行代码

<!DOCTYPE html>
<html>
<head>
    <title>X</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script>
        function requestBrands() {
            const adress = "http://localhost:3000/brands?callback=?"
            $.getJSON(adress ,function(answer) {
                const ul = document.getElementById("x");
                // 每次加载前先清空原有列表,避免重复插入
                ul.innerHTML = '';
                // 遍历返回的brands数组
                $.each(answer.brands, function(index, brand) {               
                    // 生成li元素
                    const li = document.createElement('li');
                    // 填入品牌名称,也可以按需添加id等属性
                    li.textContent = brand.name;
                    // 插入到ul中
                    ul.appendChild(li);
                })
            })
        };
    </script>
</head>
<body>
    <div>
        <!-- 修正函数名和定义的一致 -->
        <button onclick="requestBrands()">Brands categ</button>
    </div>
    <div>
        <!-- 修正h3标签多余的引号 -->
        <h3>Brands</h3>
        <ul id="x">
        </ul>
    </div>
</body>
</html>

如果你更偏好纯jQuery写法,遍历部分也可以替换成:

$.each(answer.brands, function(index, brand) {
    $('#x').append(`<li>${brand.name}</li>`)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:54:04