Ajax를 사용하여 Javascript 배열을 PHP로 전송 (PHP에서 배열을 에코 할 수 없음)

Sep 10 2020

간단한 버튼이있는 양식이 있습니다. 버튼을 클릭하면 기능 delete_data()이 호출됩니다. 이 함수는 배열을 데이터로 채 웁니다. 이 배열을 Ajax를 사용하여 PHP로 보내고 싶습니다.

문제점 : event.preventDefault();JavaScript 코드에서 볼 수 있듯이를 사용할 때 성공 경고 메시지가 표시되지만 ( "OK") PHP 스크립트에서 에코를 얻지 못합니다.

아래 코드를 수정하거나 무엇이 잘못되었는지 알려 주실 수 있습니까? 감사합니다!

HTML 코드

<form id="form" method="POST"> 
      <button type="button"id="delete" onclick="delete_data();" name="delete"><i class="fa fa-remove" aria-hidden="true"></i> Delete Zone(s)</button>
</form>

자바 스크립트 코드

function delete_data(){
        
        event.preventDefault();
        
        var checkedIds = $(".chk:checked").map(function() { return this.id; }).toArray(); var Arr = JSON.stringify(checkedIds); $.ajax({
            type: "POST",
            url: "./delete_measurement.php",
            data: {arr: Arr}, 
            cache: false,
            
            success: function(){
                alert("OK");
            }

        });

PHP 코드

<?php
include_once("./conn.php");
    
if(isset($_POST['arr'])){ $arr = json_decode($_POST['arr']); echo $arr; //can't echo
    
}else{ 
    echo "Failed";
    
}
?>

답변

1 Wimanicesir Sep 10 2020 at 18:22

에코가 보이지 않는 것은 논리입니다. 다음과 같이 성공 함수에 매개 변수를 추가하십시오.

    $.ajax({
        type: "POST",
        url: "./delete_measurement.php",
        data: {arr: Arr}, 
        cache: false,
        
        success: function(data){
            // This will show what you echo in PHP (in the console)
            console.log(data)
            alert("OK");
        }

    });