2010-03-03 95 views
3

这是我到目前为止。请阅读代码中的评论。它包含我的问题。如何显示JSON对象的值?

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。

回答

6

如果servlet 已经返回JSON(如URL似乎暗示),你并不需要解析它在jQuery的$.getJSON()功能,但只是手柄它作为JSON。摆脱jQuery.parseJSON()。这会让事情变得更糟。 getFacilityOption()函数应该用作$.getJSON()的回调函数,或者您需要将其逻辑写入function(opts)(实际上是当前的回调函数)。的

{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"} 

JSON字符串...访问时将返回 “史丹利家具” 如下

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

+0

什么? JSON是JavaScript对象的字符串表示形式,因此如果您想以常规对象的形式访问它,它*就会*需要解析... – James 2010-03-03 17:44:06

+0

'$ .getJSON'已经这样做了。 – BalusC 2010-03-03 17:45:12

+0

啊,好点。 – James 2010-03-03 17:51:52

2

getJSON将触发异步XHR请求。由于它是异步的,所以不知道它何时会完成,这就是为什么你将回调传递给getJSON - 以便jQuery在完成时能让你知道。因此,变量customer仅在请求完成后才会分配,而不是前一分钟。

parseJSON返回一个JavaScript对象:

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

..但是,作为BalusC说,你不需要解析什么,因为jQuery不会为你,然后通过所产生的JS对象回调功能。

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]); 
    } 
} 
+0

我不认为你的代码工作。抱歉。它返回[object Object]。 :(:(:( – 2010-03-03 19:29:10

+0

对不起,现在尝试使用for()循环 – 2010-03-03 22:46:12