2012-06-26 2 views
1

jquery 및 JSON을 처음 사용합니다. 다음 JSON 구조가 있습니다. 그래서, 내가 무엇을 얻으려고하는 상태를 포함하는 변수와 교외를 포함한 배열이jquery를 사용하여 JSON 구조를 반복하려는 경우

$.ajax({ 
    type:'POST', 
    url: 'getAddress.php', 
    data:postCode='+postCode', 
    success: function(response) { 
     alert(response) 
    } 
}); 

입니다 :

{ 
    "address":{ 
     "suburb":[ 
     "HACKHAM WEST", 
     "HUNTFIELD HEIGHTS", 
     "ONKAPARINGA HILLS", 
     "m" 
     ], 
     "state":"SA" 
    } 
} 

그래서 기본적으로는 위의이의 응답입니다.

+0

'$ .ajax'에 '데이터'가 잘못되었습니다. 그것은'data : 'postCode ='+ postCode, ' –

답변

5

는 유효 Ajax 요청을 확인합니다. $.ajax은이 작업을 수행 할 수 있습니다.

$.ajax({ 
    type:'POST', 
    url: 'getAddress.php', 
    data: 'postCode='+postCode, // make sure this line is correct 
    dataType: 'json', // this tells jQuery to parse it for you 
    success: function(response) { 
     var state = response.address.state; 
     var suburbs = response.address.suburb; 
    } 
}); 
+1

이되어야합니다. 그렇다면 dataType이'json '이어야합니다. Thanks – user933791

+1

@ user933791 서버가 json을 반환 할 것으로 예상되면 json을 데이터 유형으로 지정할 수 있습니다. 서버에서 적절한 헤더를 반환하면 jQuery *가 json으로 인식 할 수 있지만 일반적으로이를 지정하는 것이 좋습니다. –

+2

@ user933791 예. 그렇지 않으면,'getAddress.php'는 헤더에 다음과 같은 내용 유형을 보내야합니다 :'header ("Content-Type : application/json");'. – VisioN

3

이 트릭

$.ajax({type:'POST', 
    url: 'getAddress.php', 
    dataType: 'json', 
    data:'postCode='+postCode, 
    success: function(response) { 
     var state = response.address.state; 
     var suburbs = response.address.suburb; 
    } 
}); 

추가 dataType:'json'을하고 data 매개 변수를 고정해야한다. 당신은 당신이 얻을 JSON을 구문 분석 할 필요가

$.ajax({ 
    type: "POST", 
    url: "getAddress.php", 
    data: { 
     postCode : postCode   // data as object is preferrable 
    }, 
    dataType: "json",    // to parse response as JSON automatically 
    success: function(response) { 
     var state = response.address.state; 
     var suburbs = response.address.suburb; 
    } 
}); 
1

:

+0

+1, 의견에 감사드립니다. –

+0

@ClaudioRedi : :-) –

관련 문제