2010-03-03 7 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"}. 내가 궁극적으로 원하는 건, 만약 내가 키를 넘겨 준다면, 나는 Stanley Furniture을 되찾고 싶고, 내가 Stanley Furniture을 넘겨 준다면, 3이 돌아왔다. 3은 customerId이고 Stanley Furniture은 내 데이터베이스의 customerName입니다.

답변

6

하면 JSON과 서블릿 이미 반환 JSON (URL이 제안하는 것 같은), 당신은 jQuery의 $.getJSON() 기능에 구문 분석 할 필요는 없지만 단지 핸들 그것. 그 jQuery.parseJSON()을 제거하십시오. 잠재적으로 상황이 더욱 악화 될 것입니다. getFacilityOption() 함수는 $.getJSON()의 콜백 함수로 사용하거나 function(opts) (실제로는 현재 콜백 함수)에 논리를 작성해야합니다. 액세스 할 때 JSON에 대한 자세한 내용은

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

을 다음과 같이

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

JSON 문자열은 ... 난 강력하게 this article을 통해 이동하는 것이 좋습니다 "스탠리 가구"를 반환합니다. $.getJSON에 대해 자세히 알아 보려면 its documentation을 확인하십시오.

+0

무엇? JSON은 JavaScript 객체의 문자열 표현이므로 일반 객체로 액세스하려는 경우 구문 분석이 필요합니다. – James

+0

'$ .getJSON'은 이미 그렇게합니다. – BalusC

+0

아, 좋은 지적이야. – James

2

getJSON은 비동기 XHR 요청을 실행합니다. 비동기식이므로 완료 시점을 알려주지 않으므로 getJSON에 콜백을 전달하여 jQuery가 완료 될 때이를 알릴 수 있습니다. 따라서 변수 customer은 요청이 완료되면 잠시 후에 만 ​​할당됩니다.

parseJSON는 자바 스크립트 객체 반환 BalusC가 말한대로, 당신은 아무것도를 구문 분석 할 필요가 없습니다,

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

을 ..하지만 이후 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]를 반환합니다. :(:( –

+0

죄송합니다 ... 지금 for() 루프를 사용해보십시오 –

관련 문제