【问题标题】:Javascript: Trouble parsing json responseJavascript:无法解析 json 响应
【发布时间】:2013-04-21 18:04:30
【问题描述】:

Spring 正在返回一个具有四个属性的 json 编码对象。其中之一是名为“array”的属性。我想要这个数组的内容。

这是整个 json 响应:

ee
{"map":null,"array":[{"id":2,"description":"Cloud For Dev","businessSize":2,"businessType":9,"businessLocation":3},{"id":3,"description":"Cloud For Prod","businessSize":2,"businessType":9,"businessLocation":3}],"string":null,"bool":false}
0

我实际上并不确定“ee”或 0 是什么意思......无论如何,我试图像这样解析它:

$.ajax({
    type: "GET",
    url: "/ajax/rest/teamService/list",
    dataType: "json",
    success: function (response) {
        var teamArray = response.array;

        var $el = $("#teamSelect");
        $el.empty(); 

        $.each(teamArray[0], function(team) {
                alert(team.description);
                $el.append($("<option></option>").attr("value", team.id).text(team.description));
        });

        // Reattach the plugin
        $("#teamSelect").selectbox("detach");
        $("#teamSelect").selectbox("attach");
    },
    error: function (jqXHR, textStatus, errorThrown) {
        if (textStatus === 'error') {
            setTimeout(function() { window.location = '/do/login'; }, 7000);
        }
    }
});

我弹出了 6 次警告框(应该是 2 次),每次都显示“未定义”而不是实际描述。

选择框本身有四个空选项。

似乎我正在迭代 json 编码对象的四个参数,而不是封闭数组的两个内容。

我该如何解决这个问题?

【问题讨论】:

  • 这根本不是一个有效的 JSON 字符串。那些 "ee" 和 0 搞砸了语法,无法解析响应。
  • 我也怀疑这两个位。我在 fiddler 显示的 json 响应中看到了它们,我不确定它们是什么意思。

标签: javascript jquery json spring


【解决方案1】:

试试这个 - teamArray[0] 应该只是 teamArray

$.each(teamArray, function(i,team) {
    alert(team.description);
    $el.append($("<option></option>").attr("value", team.id).text(team.description));
});

【讨论】:

  • 这会导致它弹出 undefined 两次,这是正确的次数。 team.description 和 team.id 为空。如此接近,但还不正确。
  • 返回正确的数据。问题解决了,但为什么是“这个”而不是“团队”?
  • $.each(teamArray, function(i,team){ team.description} 你只有一个参数,这就是它不起作用的原因...查看更新的代码以将其与team 一起使用
【解决方案2】:

现在,您正在循环遍历 teamArray[0] 的键,因此有六个警报。循环teamArray。另外,$.each 的回调 takes indexInArray, valueOfElement。最好不要通过 jQuery:

for(var i = 0; i < teamArray.length; i++) {
    var team = teamArray[i];
    ...
}

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多