JSON Return을 사용한 PHP 스크립트에 대한 jQuery AJAX 호출
이것 때문에 머리를 벽에 부딪쳐 봤어요.스택오버플로우에서 많은 솔루션을 시도해 봤지만 효과가 있는 솔루션을 찾을 수 없었어요!
기본적으로 AJAX를 POST하면 PHP는 JSON을 반환하지만 AJAX는 값 대신 Undefined로 표시됩니다.
JS:
/* attach a submit handler to the form */
$("#group").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
$("#result").html('');
/* get some values from elements on the page: */
var val = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "inc/group.ajax.php",
type: "post",
data: val,
datatype: 'json',
success: function(data){
$('#result').html(data.status +':' + data.message);
$("#result").addClass('msg_notice');
$("#result").fadeIn(1500);
},
error:function(){
$("#result").html('There was an error updating the settings');
$("#result").addClass('msg_error');
$("#result").fadeIn(1500);
}
});
});
PHP:
$db = new DbConnector();
$db->connect();
$sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
.'FROM '.GROUP_TBL.' grp '
.'LEFT JOIN members USING(group_id) '
.'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';
$result = $db->query($sql);
$row = mysql_fetch_array($result);
$users = $row['users'];
if(!$users == '0'){
$return["json"] = json_encode($return);
echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
}else{
$sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
$result = $db->query($sql2);
if(!$result){
echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
}else{
echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
}
}
파이어 버그로 인한 JSON 결과:
{"status":"success","message":"success message"}
AJAX JSON 결과가 Undefined(정의되지 않음)로 표시되며 그 이유를 알 수 없습니다.추가 표시를 시도했습니다.dataType='json'
그리고.datatype='json'
. 저도 한번 바꿔봤어요.data.status
그리고.data['status']
그래도 기쁨은 없다.
어떤 도움이라도 주시면 감사하겠습니다.
성공하다dataType
대신datatype
.
그리고 당신의 아약스 요청은 json을 기대하며 json을 제외한 어떤 것도 받아들이지 않기 때문에 아래 코드를 php에 추가합니다.
header('Content-Type: application/json');
firebug에 표시되는 응답은 텍스트 데이터입니다.확인.Content-Type
확인할 응답 헤더의 값을 지정합니다(응답이 json인지 여부).그럴 것 같네요.application/json
위해서dataType:'json'
그리고.text/html
위해서dataType:'html'
.
다음을 사용할 것을 권장합니다.
var returnedData = JSON.parse(data);
JSON 문자열(텍스트만 있는 경우)을 JavaScript 개체로 변환합니다.
parseJ 사용SON jquery 메서드를 사용하여 문자열을 객체로 변환
var objData = jQuery.parseJSON(data);
이제 코드를 쓸 수 있습니다.
$('#result').html(objData .status +':' + objData .message);
서버에서 콘텐츠유형 헤더를 송신하려고 합니다.에코하기 직전에 이것을 사용합니다.
header('Content-Type: application/json');
데이터 형식이 잘못되었습니다. dataType의 데이터 형식을 변경하십시오.
언급URL : https://stackoverflow.com/questions/19155192/jquery-ajax-call-to-php-script-with-json-return
'programing' 카테고리의 다른 글
SQL 개발자를 사용하여 자동 증가 열을 설정하는 방법 (0) | 2023.02.25 |
---|---|
각도 JS에서 양식 제출 시 작업을 위해 preventDefault 또는 false를 반환할 수 없습니다. (0) | 2023.02.25 |
반응: 기능 컴포넌트에 소품 전달 (0) | 2023.02.25 |
레퍼러를 설정하지 못했습니다.정책 오류 (0) | 2023.02.25 |
javascript에서 Java Servlet 호출 (0) | 2023.02.25 |