PHP를 사용하여 JQuery .ajax ()에 대한 적절한 성공 / 오류 메시지를 어떻게 반환합니까?
계속 오류 경고가 표시됩니다. MYSQL 부분에는 많은 문제가 있으며 쿼리가 실행되고 db에서 이메일 주소를 볼 수 있습니다.
클라이언트 측 :
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
서버 측 :
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
JSON 데이터 유형을 사용하는 경우 올바른 콘텐츠 유형을 제공해야합니다. json을 에코하기 전에 올바른 헤더를 입력하십시오.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
추가 수정 사항, 쿼리 성공 여부를 확인해야합니다.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
클라이언트 측에서 :
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
도움이 되셨기를 바랍니다.
아시다시피 주문품에 사용할 수 있습니다. 많은 도움이 여전히 여전히
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
어떤 사람들은 HTTP 상태 코드 사용을 권장하지만 저는 그 관행을 경멸합니다. 예를 들어 검색 엔진을 사용 중이고 키워드에 결과가없는 경우 404 오류를 반환하는 것이 좋습니다.
그러나 나는 그것이 잘못되었다고 생각합니다. HTTP 상태 코드는 실제 브라우저 <-> 서버 연결에 적용됩니다. 연결에 대한 모든 것이 완벽하게 진행되었습니다. 브라우저가 요청을하고 서버가 시작을 호출했습니다. 펼쳐가 '행 없음'을 반환했습니다. 페이지-그 의미 "404 페이지를 발견 수 없음"에서 아무것도 WAS 발견했다.
대신 서버 측 작업 상태에서 HTTP 계층을 분리하는 것이 좋습니다. 환불하는 대신 구매 상태와 요청 결과를 캡슐화하는 JSON 데이터 구조를 항상 반환합니다.
예를 들어 PHP에서
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
그런 다음 클라이언트 측 코드에서
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
AJAX 웹 서비스를 구축하기 위해 두 개의 개의 파일이 필요합니다.
- JQuery AJAX를 사용하여 데이터를 POST (GET 일 수 있음)로 보안 호출 자바 펼쳐
- JSON을 반환하는 PHP 웹 서비스 (배열 또는 많은 양의 데이터를 반환하는 데 편리함)
따라서 먼저 JavaScript 파일에서 JQuery 구문을 사용하여 웹 서비스를 호출합니다.
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
PHP 파일 (AJAX 호출에 mywebservice.php)에는 올바른 성공 또는 상태를 반환하기 위해 다음과 같은 내용이 포함되어야합니다.
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
상단 답변에 추가 : 다음은 PHP 및 Jquery의 샘플 코드입니다.
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP- 사용자 지정 메시지 / 상태 보내기 :
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
나는 같은 문제가 있었다. 내 문제는 내 헤더 유형이 제대로 설정되지 않았습니다.
내 json 에코 전에 추가했습니다.
header('Content-type: application/json');
서버 측 :
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
고객 입장에서 :
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
'ProgramingTip' 카테고리의 다른 글
커서 끌기로 텍스트 / 요소 선택을 방지하는 방법 (0) | 2020.10.31 |
---|---|
텍스트 정렬 : 오른쪽에 (0) | 2020.10.31 |
로컬 타일을 사용하는 TileProvider (0) | 2020.10.31 |
액션에 대한 클릭 가능한 링크가있는 iOS UITextView 또는 UILabel (0) | 2020.10.31 |
UTC 날짜와 함께 AngularJS 날짜 필터 사용 (0) | 2020.10.31 |