2010-03-03 83 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