简体   繁体   中英

accessing nested json (prepared by gson) using jquery inside a map

I have a java object like that has a couple of object fields which have basic fields in them, here is an example:

Template {
    String name;
    EmailMessage defaultEmailMessage;
}
EmailMessage {
    String emailSubject;
    String emailBody;
}

I have a spring controller method that returns a list of templates in json format using gson.

In my jsp I use a jquery ajax call to get this list and then populate some html content based on it, here is a shortened version:

$.ajax({
    type : "GET",
    url : '<c:url value="/listTemplates.htm"/>',
    dataType: 'json',
    success : function(templates) {
    var map = $.map(templates, function(template) { 
        return { 
            "name": template.name,
            "emailSubject": template.defaultEmailMessage.emailSubject
    };});
        $("#thumbnails-ul").html($("#campaignThumbTmpl").tmpl(map));
    },
    error : function(data) {
        alert(data.responseText);
    }
});

In firebug I see an error undefined template.defaultEmailMessage but when I debug I can evaulate both template.defaultEmailMessage and template.defaultEmailMessage.emailSubject . I tried using $.each but same problem. How can I access nested json? If you want to see the full output of json in the browser, please let me know.

Replace your "emailSubject": template.defaultEmailMessage.emailSubject with "emailSubject": template.defaultEmailMessage

ADDED LATER: Why do you want to convert the data into json again ? you are requesting the data as json and again you are returning the json data into the template for compilation.Put the data directly into the template.

$.ajax({
          type:"GET",
          url:"<c:url value="/listTemplates.htm"/>",
          datatype:"application/json",
          success:function(templates){      
                   $.get("Put Your Template URL HERE",function(template}
                   var result = _.template(template);                                $("#thumbnails-ul").html($("#campaignThumbTmpl").tmpl(templates));
        });
             }
    }); 

This way you will be able to put the data wherever you want in your template by accessing it through .each loop as below:

 <% _.each(data,function(anynamehere){ %>
        <li><a href="<%= anynamehere.name %>"></li>
    <% }); %>

The above is a sample to print your name from the class but with other .each loop you can put other properties too....hope this helped...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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