如何显示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。
如果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的更多信息,我强烈建议您阅读本文 。 要了解有关$.getJSON
更多信息,请查看其文档 。
getJSON
将触发异步XHR请求。 由于它是异步的,因此无法确定它何时完成,这就是你将回调传递给getJSON
– 这样jQuery可以让你知道它什么时候完成。 因此,变量customer
仅在请求完成后分配,而不是在之前的某个时刻分配。
parseJSON
返回一个JavaScript对象:
var parsed = jQuery.parseJSON('{"foo":"bar"}'); alert(parsed.foo); // => alerts "bar"
..但是,正如BalusC所说,你不需要解析任何东西,因为jQuery为你做了这些,然后将生成的JS对象传递给你的回调函数。
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]); } }