Reputation: 2471
A Beginner's question: Here's my server side code, very simple:
@GET
@Path("/query")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<Integer,String> getUsers(
@QueryParam("from") int from,
@QueryParam("to") int to) {
Map<Integer, String> orders = new HashMap<Integer,String>();
orders.put(1, "order1");
orders.put(2, "order2");
orders.put(3, "order3");
return orders;
}
Here's my JQuery code:
$(document).ready(function() {
$('#id1').mouseover(function() {
alert("ok");
var formData = {from:3, to:2};
var result = $.ajax({
url: 'http://localhost:8080/MyJSON/resources/entities.customer/query',
type: "GET",
data: formData,
dataType: 'json',
success: function (data) {alert(data);}
});
});
}); // end ready
How do I parse the data object and get the json, which is {"1":"order1","2":"order2","3":"order3"}
Upvotes: 0
Views: 1670
Reputation: 87073
success: function (data) {
alert(data['1']); // output: order1
alert(data['2']); // output: order2
}
Using jQuery $.each()
loop:
success: function (data) {
$.each(data, function(key, val) { // here key = 1, 2, 3...
alert(val); // output: order1, order2...
});
}
Using vanilla javascript loop
for(var key in data) {
// key = 1, 2, 3...
alert(data[key]); // output: order1, order2...
}
As you set dataType: 'json'
is ajax config, so you don't need any extra parsing effort like $.parseJSON()
or JSON.parse()
.
Upvotes: 2