简体   繁体   English

解析来自Servlet的JSON响应

[英]Parse JSON response from Servlet

Ok, Ive got a Java Servlet returning some JSON (In Application/JSON format). 好的,我有一个Java Servlet返回了一些JSON(以Application / JSON格式)。 To do this, im using the GSON libary. 为此,我使用GSON库。

The Servlets GET method takes one paramater, ID. Servlet的GET方法采用一个参数ID。 The servlet seems to be working, For example,chrome shows my AJAX GET request returning the following when the [Booking]ID paramater sent is 1. servlet似乎正在运行,例如,chrome发送的[Booking] ID参数为1时,chrome显示了我的AJAX GET请求,返回以下内容。

    0: {WidgetID:46, BookingID:1, X:393, Y:50, Content:Test1}
    1: {WidgetID:47, BookingID:1, X:337, Y:251, Content:Test2}
    2: {WidgetID:48, BookingID:1, X:97, Y:198, Content:Test3}

The problem I have is with parsing this response. 我的问题是解析此响应。 Here is my JS code: 这是我的JS代码:

\n    loadPositions() { loadPositions(){\n    var BookingID = var BookingID = \n    if (BookingID != null && BookingID != "null") 如果(BookingID!= null && BookingID!=“ null”)\n    { {\n    var data = {"id" : BookingID}; var data = {“ id”:BookingID};\n    $.getJSON("Widget", data, function(data) { $ .getJSON(“ Widget”,data,function(data){\n    // Successfully got all this bookings widgets as JSON, TODO: Parse this! //成功将所有预订小部件作为JSON,TODO:对此进行解析!\n    }); });\n    } }\n    } } 

What should I put in the "TODO: Parse this!" 我应该在“ TODO:对此进行解析!”中输入什么? section? 部分? I want to foreach over all the elements, and grab their data. 我想介绍所有元素,并获取它们的数据。 I really suck at this JQuery stuff. 我真的很讨厌这个JQuery的东西。

In the todo section, you should do the following to loop through all the arrays: 在todo部分中,您应该执行以下操作遍历所有数组:

$.each(data, function(index,value){
    // here index=0 & value.WidgetID=46, value.BookingId = 1, use it as you would like to.

})

Have a look at jQuery .each() 看看jQuery .each()

http://api.jquery.com/jQuery.each/ http://api.jquery.com/jQuery.each/

and for a good example of what you want to do... 并举例说明您想做什么...

http://api.jquery.com/jQuery.getJSON/ http://api.jquery.com/jQuery.getJSON/

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM