开发者

How to use jQuery .each() - I get a value, but it's the wrong one

I am returning a JSON object (as a String) through a servlet. The JSON object looks like this:

{
  "3": "Martin Luther",
  "30": "Boris Becker",
  "32": "Joseph Goebels",
  "19": "Leonardo Da Vinci"
}

My jQuery looks like this (the submission of data is correct because I get a proper looking result from the servlet):

$.ajax({
  type: "GET",
  url: "MyServlet",
  data: queryString + "count=" + variables,
  success: function(resultObj) {
    $.each(resultObj, function(key, value) {
      $("#resultCount").html(key + ", " + value);
    });
  }
});

However when I try to print the results, that is the variables key and value, I get a number for the key but not a number from the JSONObject and an empty string instead of the value.

Essentially the questi开发者_如何学Pythonon is about how to "extract" the information from a JSON object.


Your JSON is not an array. It should look like this:

[{ "3":"Martin Luther" },
 { "30":"Boris Becker" }]

or even better:

[{ id: "3", name: "Martin Luther" },
 { id: "30", name: "Boris Becker" }]

Then you can loop:

$.each(data, function(index, item) {
    alert(item.id + ' ' + item.name);
});


Try specifying dataType as json in your AJAX call:

$.ajax( {
        type : "GET",
        url : "MyServlet",
        data : queryString + "count=" + variables,
        dataType : 'json',
        success : function(resultObj) {
          $.each(resultObj, function(key, value) {
                $("#resultCount").html(key+", "+value); 
             });
        }
    });


Couple things:

  1. You should be using the JSON data type. Try the simpler $.getJSON method.
  2. Your iteration is correct, but you'll be overwriting the previous results on each iteration (i.e. it comes out as just the Hitler entry)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜