如何显示JSON对象的值?

时间:2010-03-03 17:35:05

标签: 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
}

这是我的json对象应该是什么样的:{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}。我最终想要的是,如果我传入密钥3,我想要回复Stanley Furniture,如果我传入Stanley Furniture,我会得到3。由于3是customerId,Stanley Furniture是我的数据库中的customerName。

3 个答案:

答案 0 :(得分:6)

如果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

答案 1 :(得分:2)

getJSON将触发异步XHR请求。由于它是异步的,因此无法确定它何时完成,这就是你将回调传递给getJSON的原因 - 这样jQuery可以让你知道它什么时候完成。因此,变量customer仅在请求完成后分配,而不是在片刻之前分配。

parseJSON返回一个JavaScript对象:

var parsed = jQuery.parseJSON('{"foo":"bar"}');
alert(parsed.foo); // => alerts "bar"

..但是,正如BalusC所说,你不需要解析任何东西,因为jQuery为你做了这些,然后将生成的JS对象传递给你的回调函数。

答案 2 :(得分:2)

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]);   
  }
}
相关问题