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

Ajax获取Spring服务JSON填充下拉框时遇JSON解析错误

解决Ajax获取JSON后填充下拉框时的"Unexpected token o"错误

错误原因分析

你遇到的Unexpected token o in JSON at position 1错误,根源在于重复解析JSON:
你在Ajax请求里设置了dataType: "json",这会让jQuery自动把服务器返回的JSON字符串转换成JavaScript对象。但你又调用了jQuery.parseJSON(data.dimensions),而data.dimensions已经是一个JS对象了,不是JSON字符串——当你把对象传给parseJSON时,它会先把对象转成字符串"[object Object]",解析这个字符串自然会报错。

完整解决方案

下面是修正后的代码,包含HTML结构、Ajax请求和通用的下拉框填充函数:

1. HTML结构(三个目标下拉框)

<select id="colorSelect"></select>
<select id="dimensionSelect"></select>
<select id="productSelect"></select>

2. 修正后的Ajax请求

jQuery.ajax({
  dataType: "json",
  type: "get",
  url: "你的Spring接口地址", // 替换成实际的接口URL
  success: function (data, status, jqXHR) {
    // 分别填充三个下拉框
    helpers.buildDropdown(data.colors, $('#colorSelect'), '选择颜色');
    helpers.buildDropdown(data.dimensions, $('#dimensionSelect'), '选择尺寸');
    helpers.buildDropdown(data.products, $('#productSelect'), '选择产品');
  },
  error: function (jqXHR, status) {
    console.error('请求失败:', status);
  }
});

3. 实现helpers.buildDropdown工具函数

这个函数用来通用处理下拉框填充,支持传入数据源、目标DOM元素和默认提示文本:

var helpers = {
  buildDropdown: function(data, dropdownElement, defaultText) {
    // 先清空下拉框原有内容
    dropdownElement.empty();
    
    // 添加默认提示选项
    dropdownElement.append($('<option>').val('').text(defaultText));
    
    // 遍历数据源,添加选项
    $.each(data, function(index, item) {
      // 根据你的数据结构,用item.id作为选项值,item.name作为显示文本
      dropdownElement.append($('<option>').val(item.id).text(item.name));
    });
  }
};

关键注意点

  • 不要对已经被jQuery解析过的JS对象再调用jQuery.parseJSON(),直接使用data.colors、data.dimensions、data.products即可。
  • 确保你的Spring接口返回的是标准JSON格式(你提供的示例JSON是符合要求的)。
  • 如果不需要默认提示选项,可以去掉添加默认选项的那一行代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:13:17