如何显示JSON对象的值?

Tha*_*ham 3 javascript jquery json jsp

这是我到目前为止所得到的.请阅读代码中的注释.它包含我的问题.

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
}
Run Code Online (Sandbox Code Playgroud)

这是我的json对象应该是这样的:{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}.我最终想要的是,如果我传递钥匙3,我想Stanley Furniture回来,如果我传入Stanley Furniture,我得到了3回来.既然3Stanley FurniturecustomerId,那么我的数据库中就是customerName.

Bal*_*usC 6

如果servlet 已经返回JSON(如URL似乎建议的那样),则不需要在jQuery的$.getJSON()函数中解析它,而只需将其作为JSON 处理.摆脱它jQuery.parseJSON().这会使事情变得更糟.该getFacilityOption()函数应该用作回调函数,$.getJSON()或者你需要在其中编写其逻辑function(opts)(实际上是当前的回调函数).

一个JSON字符串

{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
Run Code Online (Sandbox Code Playgroud)

......如果按以下方式访问,将返回"Stanley Furniture"

var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
alert(json['3']);
// or
var key = '3';
alert(json[key]);
Run Code Online (Sandbox Code Playgroud)

要了解有关JSON的更多信息,我强烈建议您阅读本文.要了解更多信息$.getJSON,请查看其文档.