Skip to content Skip to sidebar Skip to footer

How Do I Display Values Of An Json Object?

Here is what I got so far. Please read the comment in the code. It contains my questions. var customer; //global variable function getCustomerOption(ddId){ $.getJSON('htt

Solution 1:

If the servlet already returns JSON (as the URL seem to suggest), you don't need to parse it in jQuery's $.getJSON() function, but just handle it as JSON. Get rid of that jQuery.parseJSON(). It would make things potentially more worse. The getFacilityOption() function should be used as callback function of $.getJSON() or you need to write its logic in the function(opts) (which is actually the current callback function).

A JSON string of

{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}

...would return "Stanley Furniture" when accessed as follows

var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
alert(json['3']);
// orvar key = '3';
alert(json[key]);

To learn more about JSON, I strongly recommend to go through this article. To learn more about $.getJSON, check its documentation.

Solution 2:

getJSON will fire an asynchronous XHR request. Since it's asynchronous there is no telling when it will complete, and that's why you pass a callback to getJSON -- so that jQuery can let you know when it's done. So, the variable customer is only assigned once the request has completed, and not a moment before.

parseJSON returns a JavaScript object:

var parsed = jQuery.parseJSON('{"foo":"bar"}');
alert(parsed.foo); // => alerts "bar"

.. but, as BalusC has said, you don't need to parse anything since jQuery does that for you and then passes the resulting JS object to your callback function.

Solution 3:

var customer;   //global variablefunctiongetCustomerOption(ddId){
      $.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
           $('>option', dd).remove(); // Remove all the previous option of the drop downif(opts){  
                customer = opts; //Attempt to parse the JSON Object.
           }
      });
}

functiongetFacilityOption(){
  for(key in costumer)
  {
    alert(key + ':' + costumer[key]);   
  }
}

Post a Comment for "How Do I Display Values Of An Json Object?"