使用 Ajax 将 Javascript 数组发送到 PHP(无法从 PHP 回显数组)



我有一个表单,里面有一个简单的按钮。点击按钮时,会调用函数delete_data()。此函数用数据填充数组。我想用Ajax将这个数组发送到PHP。

问题:如您在我的JavaScript代码中所见,当使用event.preventDefault();时,会显示成功警报消息("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>

JavaScript代码

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";

}
?>

这是一种逻辑,你看不到回声。为成功函数添加一个参数,如下所示:

$.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");
}
});

最新更新