2011-08-27 3 views
1

기본적으로 JSON 오류 또는 성공으로 반환하는 파일에 간단한 ajax 쿼리가 있습니다.간단한 jquery/json 함수로 무엇이 누락 되었습니까?

예 :

{"error":"1"}{"error_msg":" Invalid Expiry Date. Your credit card has not been billed for this transaction."} 

문제는 그러나 내 아약스 포스트에서이 JSON 데이터 수익을 얻고있다하더라도, 나는 모든 데이터에 액세스 할 수없는 것이다.

내 JQuery와는 다음과 같은 : 경고의

 $.ajax({ 
      type: 'POST', 
      url: 'process_sale.php', 
      data: $(this).serialize(), 
      cache: false, 
      dataType: 'json', 
      success: function(data) { 

      if(data['success']=='1'){ 

       alert('hi'); 

       $('#feedback').html('<strong>Congratulations</strong'); 

      } 

      if(data['error']=='1') { 

       alert('hi'); 

       $('#feedback').html(data['error_msg']); 


      } 

        // this following alert does nothing, because its empty even if the json 
        // returns what I pasted above example result. 

        alert(data['error'] + ' ' + data['success']); 

      } 
     }); 

아무도 아무것도 할 수 없습니다.

내가 여기에 정말 분명한 것을 놓치고 있습니까? 나는 내가 일하고있는 다른 코드와 상당히 똑같은 것처럼 보이기 때문에 이것이 왜 작동하지 않는지에 대해 머리를 감싸는 것처럼 보일 수 없다.

+0

AJAX 응답도 오류 (2xx가 아닌) 상태를 반환합니까? 그렇다면 성공 콜백은이를 포착하지 않습니다. –

답변

4

잘못된 JSON을 구문 분석하려고합니다. 예에서 두 개의 인접한 JSON 개체가 있습니다. 코드의 나머지 부분을 바탕으로

// You want this: 
{"error":"1", // note , not {} 
"error_msg":" Invalid Expiry Date. "+ 
       "Your credit card has not been billed for this transaction."} 

// or this (notice the `,` and the `[`, and `]`) 
[{"error":"1"},{"error_msg":" Invalid Expiry Date. Your credit card has not been billed for this transaction."}] 

, 내가 첫 번째가 더 나은 사용자의 요구를 충족시킬 것이라는 내기 것이다 : 당신은 배열에 배치하거나, ​​JS가 그들을 이해하려면 그들에게 하나 개의 객체를 만들기 위해 하나 필요 .

{"error":"1","message":"This is an error message"} 

Ajax 호출 : 당신은 아마 JSON 데이터는이를 좋아한다 오류 메시지 데이터 [ '오류']가 아닌 데이터 [0] [ '오류']

+0

물론. 얼마나 어리석은 짓이야! 고마워. – willdanceforfun

1

에 액세스하는 것을 선호 위하여려고하고있다 :

$.ajax({ 
      type: 'POST', 
      url: 'process_sale.php', 
      data: $(this).serialize(), 
      cache: false, 
      dataType: 'json', 
      success: function(data) { 
      if (data != null){ 
      if(data.error=='0'){ 

       alert('Success'); 

       $('#feedback').html('<strong>Congratulations</strong'); 

      } 

      if(data.error=='1') { 

       alert('Error occurred'); 

       $('#feedback').html(data.mesage); 


      } 
      }else{ 
       //do something with NULL 
      } 

      } 
     }); 
관련 문제