nedal jedidi
nedal jedidi

Reputation: 77

iterate map with jquery

will i'm using spring mvc with ajax for my application , my issue is that i don't know how i can iterate a map that i sent from spring controller.

Controller code

                    ObjectMapper mapper = new ObjectMapper();
                    String json = "";
                    try {

                        json = mapper.writeValueAsString(ser.StatistiquesCompte());
                    } catch (Exception e) {
                        System.out.println("erreur ici");
                    }

                     return json;

and my ajax code look like that :

            $.ajax({
                url : 'Stats',
                success : function(data) {
                    alert(data);
                }
            });

my result is like that : {"Key":10,"Key1",30} how i am supposed to iterate this map.

Upvotes: 0

Views: 3687

Answers (3)

Sasanka Panguluri
Sasanka Panguluri

Reputation: 3138

If you already know what keys are in your response JSON (which holds good for any design that returns JSON responses), the best thing to do is use JSON.parse:

      $.ajax({
            url : 'Stats',
            success : function(data) {
                var json = JSON.parse(data);
                alert(json.Key1);
                alert(json.Key);
            }
        });

Upvotes: 0

Ahmad
Ahmad

Reputation: 1931

using a for loop

$.ajax({
    url: 'Stats',
    success: function (data) {
        for (var item in data) {
            // log key , value
            console.log(item, data[item]);
        }

    }
});

Upvotes: 1

Ranjith
Ranjith

Reputation: 2819

Itreate your response data like this

$.ajax({
    url : 'Stats',
    success : function(data) {
         $.each(data , function( key, value ) {
             console.log( key + ": " + value ); // Key : 10
         });
    }
});

Upvotes: 0

Related Questions