问题描述
我有一个带有简单按钮的表单。单击按钮时,将调用功能delete_data()
。此函数用数据填充数组。我想将此数组通过Ajax发送到PHP。
问题:当您在我的JavaScript代码中使用event.preventDefault();
时,显示成功警报消息(“确定”),但是我没有从我的回声中获取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");
}
});