2009-08-11 6 views
20

아래의 jquery 스크립트에 문제가 있습니다.이 스크립트는 기본 버전에서 제외되었으며 심지어 작동하지 않습니다. jquery 스크립트가 호출하는 PHP 파일이 있습니다. to, 인코딩하고 json 응답을 표시하도록 설정했습니다.jquery 스크립트에서 변수에 jSON 응답을 얻는 방법

그런 다음 jquery 스크립트에서 값을 읽고 응답해야하지만 응답을받지 못합니다.

json.response가 이름 응답 인 json 문자열에서 변수를 호출하는 잘못된 방법입니까?

는 누군가의 도움이 나는

<?PHP 
header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 
header('Content-type: application/json'); 

// set to retunr response=error 
$arr = array ('resonse'=>'error','comment'=>'test comment here'); 
echo json_encode($arr); 
?> 

//the script above returns this: 
{"response":"error","comment":"test comment here"} 

<script type="text/javascript"> 
$.ajax({ 
    type: "POST", 
    url: "process.php", 
    data: dataString, 
    dataType: "json", 
    success: function (data) { 
     if (json.response == 'captcha') { 
      alert('captcha'); 
     } else if (json.response == 'error') { 
      alert('sorry there was an error'); 
     } else if (json.response == 'success') { 
      alert('sucess'); 

     }; 
    } 

}) 
</script> 

UPDATE 붙어 있어요시겠습니까; 내가

data.response


json.response

을 변경 한 그러나 그것은 오크 중 하나

답변

27

위의 제안 사항을 사용하도록 다시 작성된 스크립트와 no-cache 메소드가 변경되었습니다.

<?php 
// Simpler way of making sure all no-cache headers get sent 
// and understood by all browsers, including IE. 
session_cache_limiter('nocache'); 
header('Expires: ' . gmdate('r', 0)); 

header('Content-type: application/json'); 

// set to return response=error 
$arr = array ('response'=>'error','comment'=>'test comment here'); 
echo json_encode($arr); 
?> 

//the script above returns this: 
{"response":"error","comment":"test comment here"} 

<script type="text/javascript"> 
$.ajax({ 
    type: "POST", 
    url: "process.php", 
    data: dataString, 
    dataType: "json", 
    success: function (data) { 
     if (data.response == 'captcha') { 
      alert('captcha'); 
     } else if (data.response == 'success') { 
      alert('success'); 
     } else { 
      alert('sorry there was an error'); 
     } 
    } 

}); // Semi-colons after all declarations, IE is picky on these things. 
</script> 

가장 큰 문제는 여기 이것은 당신이 자바 스크립트 코드에서 잘못된 특성을 찾고 있었다 것을 의미했다. 당신이 대신 "응답"의 ("resonse을"반환 된 JSON에 오타가 있었다이었다. 한 가지 방법 앞으로 이러한 문제를 잡는 data의 값을 console.log 당신이 찾고있는 특성이 있는지 확인합니다.

Learning how to use the Chrome debugger tools을하는 것입니다 (또는 파이어 폭스/사파리/오페라/등. 유사한 도구)도 헤아릴 수 없을 것입니다.

5

당신은 json.response 대신 JS에 data.response을 사용해야하지 않았다

.

$arr = array ('resonse'=>'error','comment'=>'test comment here'); 

을 주목 mispelling이 "resonse을"

+0

방금 ​​시도했지만 다른 것을 만들지 않았 음 – JasonDavis

+0

데이터 유형을 확인할 수 있습니까? 'alert (typeof data);'성공 콜백에서이를 수행해야합니다. – RaYell

+0

그것은 "object"라고 말합니다 – JasonDavis

4

귀하의 PHP 배열로 정의된다. RaYell이 언급했듯이 함수의 매개 변수가 현재 data이므로 json 대신 data을 사용해야합니다.

맞춤법 형식 resonseresponse으로 바꾸려면 PHP 파일을 편집 해보십시오. 그때 작동합니다.

+0

문제는 고마워요, 스크립트의 1 영역에서 잡았지만 그 부분을 놓쳤습니다. – JasonDavis

관련 문제