programing

PHP를 사용하여 JQuery .ajax()에 대한 적절한 성공/오류 메시지를 반환하려면 어떻게 해야 합니까?

luckcodes 2023. 1. 31. 21:21

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 dataType을 사용하는 경우 올바른 콘텐츠 유형을 제공해야 합니다.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 상태 코드 사용을 권장하는 사람도 있지만, 저는 HTTP 상태 코드 사용을 매우 싫어합니다.검색 엔진을 실행 중이지만 제공된 키워드가 아무 결과도 없다면 404 오류를 반환하는 것이 좋습니다.

하지만 나는 그것이 잘못되었다고 생각한다.HTTP 상태 코드는 실제 브라우저 <-> 서버 연결에 적용됩니다.커넥트의 모든 것이 완벽하게 진행되었습니다.브라우저가 요청을 했고 서버가 핸들러 스크립트를 호출했습니다.스크립트가 '행 없음'을 반환했습니다."404 페이지를 찾을 수 없음"을 나타내는 페이지는 없습니다.

대신 서버 측 작업 상태에서 HTTP 계층을 분리하는 것이 좋습니다.단순히 json 문자열로 텍스트를 반환하는 대신 요청 상태와 요청 결과를 캡슐화한 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)로 전송하는 호출 Javascript
  • 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 파일(mywebservice).올바른 성공 또는 오류 상태를 반환하려면 AJAX 호출에 기재된 바와 같이 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));
    }
?>

서버 측:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

클라이언트 측:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

상위 답변에 추가: 다음은 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');

사이트 간 스크립팅 문제가 없는지 확인할 수도 있습니다.html 페이지가 다른 도메인/포트 콤비에서 온 경우, 브라우저는 콜을 차단할 수 있습니다.

보통 html 페이지에서 마우스 오른쪽-> 검사합니다.그런 다음 오류 콘솔에서 다음과 같은 오류를 찾습니다.

'에서 XMLHttpRequest에 액세스...:8080'은 원래 '...:8383'이(가) CORS 정책에 의해 차단되었습니다.요청된 리소스에 'Access-Control-Allow-Origin' 헤더가 없습니다.

언급URL : https://stackoverflow.com/questions/9676084/how-do-i-return-a-proper-success-error-message-for-jquery-ajax-using-php