简体   繁体   English

在Jquery中迭代Json对象?

[英]Iterating Json Object in Jquery?

I want to know how to iterate a JSON object using jQuery. 我想知道如何使用jQuery迭代JSON对象。 My requirement is I am getting a list from a Java Servlet to the UI and I have to populate a combo box with the AJAX response. 我的要求是要从Java Servlet到用户界面获取列表,并且必须用AJAX响应填充组合框。

The above tack I already did it using struts2 and jQuery. 上面的方法我已经使用struts2和jQuery完成了。 Now I am in the middle of nowhere, how to iterate the Java List back in JSP: 现在,我无所适从,如何在JSP中迭代Java列表:

$("#XXX option").remove(); 
$.each(data.YYYList, function(index, item) {
    $("#XXX").append($("<option></option>").text(item).val(item));
});

I have set the MIME type as response.setContentType("application/json"); 我已将MIME类型设置为response.setContentType("application/json");

Can any one please guide me how to achieve this. 谁能指导我如何实现这一目标。 Please let me know if any other information is needed from me. 请让我知道是否需要我提供任何其他信息。

Based on the small amount of information given by Esh, here is an example that I created for the very function you listed. 根据Esh给出的少量信息,这是我为列出的功能创建的示例。 I have a JSON that I want to be used in multiple select boxes. 我有一个要在多个选择框中使用的JSON。

Fiddle 小提琴

Example Json: 示例Json:

  "yyyList": [
    {
      "Id": "1",
      "Name": "aaaa "
    }, {
      "Id": "2",
      "Name": "bbb "
    }, {
      "Id": "6",
      "Name": "ccc "
    }, {
      "Id": "7",
      "Name": "ddd "
    } ]


$.ajax({
              url: "URL",
               //data: "",
               type: "GET",
               dataType: 'json',
               success: function (data) {            
               $.each(data.YYYList, function () {
                  $('#state').append('<'option value='+this.Id+'>'+this.Name+'<'option>');
               });
            }
        })

$('#state') ---> gives the same id for select tag in HTML Please make correct it option syntax $('#state') --->为HTML中的select标记提供相同的ID,请更正it选项语法

Hope this helps. 希望这可以帮助。

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

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