这是我到目前为止得到的。请阅读代码中的注释。它包含我的问题。
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
}
我的 json 对象应该如下所示:{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
。我最终想要的是,如果我传入 key 3
,我想取回 Stanley Furniture
,如果我传入 Stanley Furniture
,我得到了 3
。因为 3
是我数据库中的 customerId 而 Stanley Furniture
是 customerName。
最佳答案
如果 servlet 已经 返回 JSON(正如 URL 似乎暗示的那样),您不需要在 jQuery 的 $.getJSON()
函数中解析它,但是只需将其作为 JSON处理即可。去掉那个 jQuery.parseJSON()
。这可能会使事情变得更糟。 getFacilityOption()
函数应该用作 $.getJSON()
的回调函数,或者您需要将其逻辑写入 function(opts)
(其实就是当前的回调函数)。
一个JSON字符串
{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
...按如下方式访问时将返回“Stanley Furniture”
var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
alert(json['3']);
// or
var key = '3';
alert(json[key]);
要了解有关 JSON 的更多信息,我强烈建议您浏览 this article .要了解有关 $.getJSON
的更多信息,请查看 its documentation .
关于javascript - 如何显示 JSON 对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2373524/