jquery 스크립트에서 JSON 응답을 변수로 가져오는 방법
아래의 jQuery 스크립트에 문제가 있습니다. 이것은 기본적으로 제거된 버전이며 작동하지 않을 것입니다. jQuery 스크립트가 호출하는 php 파일을 가지고 있습니다. 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>
업데이트:
나는 변했다.
json.response
안으로
data.response
하지만 이것도 성공하지 못했습니다.
위의 제안 사항을 사용하기 위해 다시 작성한 스크립트와 노캐시 방식의 변경 사항입니다.
<?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>
여기서 가장 큰 문제는 반환하려는 JSON에 "response"가 아닌 "response"("response")라는 오타가 있다는 것입니다.이것은 당신이 자바스크립트 코드에서 잘못된 속성을 찾고 있다는 것을 의미합니다.미래에 이러한 문제를 해결하는 한 가지 방법은console.log
의 가치data
그리고 당신이 찾는 부동산이 그곳에 있는지 확인합니다.
Chrome debugger 도구(또는 Firefox/Safari/Opera/등의 유사한 도구)를 사용하는 방법을 배우는 것도 매우 유용할 것입니다.
당신은 사용해야 합니다.data.response
대신에 당신의 JS에서json.response
.
PHP 배열은 다음과 같이 정의됩니다.
$arr = array ('resonse'=>'error','comment'=>'test comment here');
철자가 틀리다는 것을 알아봅니다."resonse
". 그리고 RaYell 씨가 말씀하신 것처럼.data
대신에json
당신의success
해당 매개 변수가 현재이므로 functiondata
.
맞춤법 양식을 변경하려면 PHP 파일을 편집해 보십시오.resonse
로.response
. 그러면 될 겁니다.
이 함정을 조심하세요: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
몇 시간 전에 검색해보니 포함된 파일에 줄이 끊어졌습니다.
언급URL : https://stackoverflow.com/questions/1261747/how-to-get-json-response-into-variable-from-a-jquery-script
'programing' 카테고리의 다른 글
Wordpress 메타 쿼리는 두 키의 합을 비교합니다. (0) | 2023.10.22 |
---|---|
장고 템플릿에서 수학을 하는 방법은? (0) | 2023.10.22 |
XmlDocument를 사용하여 XML 특성 읽기 (0) | 2023.10.22 |
Angular의 $httpBackend에서 파일 내용을 반환하는 방법은 무엇입니까? (0) | 2023.10.22 |
git 하위 모듈을 하위 폴더를 가리키도록 변경하는 방법은? (0) | 2023.10.22 |