How do I display values of an JSON object?

javascript, jquery, json, jsp

Solution

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']);
// or
var 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.

Problem

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("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) { $('>option', dd).remove(); // Remove all the previous option of the drop down if(opts){ customer = jQuery.parseJSON(opts); //Attempt to parse the JSON Object. } }); } function getFacilityOption(){ //How do I display the value of "customer" here. If I use alert(customer), I got null } ``` Here is what my json object should look like: `{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}`. What I ultimately want is that, if I pass in key `3`, I want to get `Stanley Furniture` back, and if I pass in `Stanley Furniture`, I got a `3` back. Since `3` is the customerId and `Stanley Furniture` is customerName in my database.

Original source