【问题标题】:How to retrieve java Set and iterate over the values from response of ajax call?如何从 ajax 调用的响应中检索 java Set 并迭代值?
【发布时间】:2016-05-01 22:22:56
【问题描述】:

我有以下 ajax 调用

$.ajax({
    type: "GET",
    url: "../targeturl",
    data : postdata,
    contentType: 'application/json',
    success: function(response, status, request) {
    ** in response im getting three sets which i wish to iterate
     }

最后几行控制器方法如下:

JsonWrapper response = new JsonWrapper();
/*some lines to fetch data from db*/
response.addParam("vSet",vSet);
response.addParam("dSet",dSet);

return response;

由于我以前从未尝试过,请告诉我如何执行此操作。如果问题不够清楚,也请告诉我。

【问题讨论】:

  • 请提供正确的控制器代码。你在使用一些框架还是普通的 servlet?
  • JSON 的响应如何?
  • @Luiggi,我使用 spring mvc.method 返回 JsonWrapper 的 obj。

标签: javascript java json ajax


【解决方案1】:

使用 JQuery

$.each(response.vSet, function(index, element) {
    //process 
});

使用 Javascript

for(var i=0;i<response.vSet.length;i++){
  //process 
}

【讨论】:

  • 应该是response.vSet.length 而不是response.data.vSet.length
  • 在完成上述更改后,第二个对我有用。
【解决方案2】:

如果您的响应是有效的 Json,您可以使用内置函数 JSON.parse() 的 JavaScript 解析响应。然后根据您在响应中构建 json 的方式,根据需要对其进行迭代。

$.ajax({
    type: "GET",
    url: "../targeturl",
    data : postdata,
    contentType: 'application/json',
    success: function(response, status, request) {
        var json = JSON.parse(response).
        //iterate over json by accessing the indices of json.
        for(var i = 0; i < json.length; i++)
        {
            (..) //do stuff with json[i]
        }
        //or access json using the key values you specified in your response
        json['vSet'] // or json.vSet.

        console.log(json) //this will allow you to inspect your response after you parsed it to json.
     }

【讨论】:

  • 我认为在 for 循环中应该是 var 而不是 int
  • 如果我们使用您的解决方案并且响应有多个集合,就像我的情况一样,它也会变得更加复杂。
  • 你的意思是它变得更复杂了?我没有做任何与其他答案不同的事情。他以某种方式期望响应已经是具有“数据”属性的对象格式。我不明白为什么会这样,所以我先将其解析为 json。
猜你喜欢
  • 1970-01-01
  • 2016-12-09
  • 2019-05-09
  • 2021-01-19
  • 1970-01-01
  • 2011-04-22
  • 2014-09-10
  • 1970-01-01
  • 2012-03-06
相关资源
最近更新 更多