如何显示JSON对象的值? [英] 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
}
这是我的json对象的外观:{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
.我最终想要的是,如果我传递密钥3
,我想找回Stanley Furniture
,如果我传递Stanley Furniture
,我又得到了3
.由于在我的数据库中,3
是customerId,而Stanley Furniture
是customerName.
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.
推荐答案
如果servlet 已经返回JSON(如URL所示),则无需在jQuery的$.getJSON()
函数,但只需处理作为JSON.摆脱该jQuery.parseJSON()
.这会使情况变得更糟. getFacilityOption()
函数应该用作$.getJSON()
的回调函数,或者您需要在function(opts)
(实际上是当前的回调函数)中编写其逻辑.
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).
{"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]);
要了解有关JSON的更多信息,强烈建议阅读本文.要了解有关$.getJSON
的更多信息,请查看其文档.
To learn more about JSON, I strongly recommend to go through this article. To learn more about $.getJSON
, check its documentation.
这篇关于如何显示JSON对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!