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("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
ba开发者_运维技巧ck. Since 3
is the customerId and Stanley Furniture
is customerName in my database.
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.
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.
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 = opts; //Attempt to parse the JSON Object.
}
});
}
function getFacilityOption(){
for(key in costumer)
{
alert(key + ':' + costumer[key]);
}
}
精彩评论