【问题标题】:Access List of json object in ajax responseajax响应中json对象的访问列表
【发布时间】:2013-11-05 03:56:59
【问题描述】:

也许我有一个类似的问题,但我无法为这个问题找到正确的关键字,所以请多多包涵。

我在可能的java类中有这样的数据

List<String> listOne = some data list from the database
List<String> listTwo = another data list from the database

我想首先将这两个 List 作为 json 对象发送给客户端所以我的想法是这样的:

要么

Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put( listOne );
map.put( listTwo );

return new Gson().toJson( map );

或者

List<List<String>> list = new ArrayList<List<String>>();
list.add( listOne );
list.add( listTwo );

return new Gjson().toJson( map );

我不知道哪个更好。 接下来我要做的是访问客户端

$.post( 'some url', someData : 'that requires to know which data will be fetched',
        function( data ) {
        // here how can I access the two list inside the list
        // or the list inside the map
        // i want to have a full control to the data 
        // example:
        //    Iterate the listOne on this $('#someId').append( listOne );
        //    Iterate the listTwo on this $('#anotherId').append( listTwo );

      }, json);

正确执行此操作的方法是什么?如果我的问题不清楚,请发表评论,我会做出相应的回应。提前致谢

【问题讨论】:

    标签: java jquery ajax json gson


    【解决方案1】:

    首先,您应该将代码修复为:

    Map<String, List<String>> map = new HashMap<String, List<String>>();
    map.put("listOne", listOne );
    map.put("listTwo", listTwo );
    
    return new Gson().toJson( map );
    

    其次,你应该使用$.GetJSON()函数:

    $.getJSON( 'some url', function( data ) {
       //Do something with data
    
    });
    

    然后您可以使用data.listOnedata.listTwo 直接访问数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      相关资源
      最近更新 更多