我开始学习使用PHP和Ajax进行Wordpress插件开发。 在插件中我想从数据库中删除日期。 因此,我开发了一个fancybox,用户可以在其中查看有关id的信息 对象和用户都可以删除对象。
删除对象的ajax函数效果很好,但我没有从jason / ajax获得状态“OK”。 因此,如果对象已被删除,该函数不会向我显示消息“成功”并且不会关闭fancybox。
如果我刷新了页面,则该对象已被删除。
我想做错了,我的错误在哪里?
感谢您的反馈。
删除数据的Ajax函数:
add_action( 'wp_ajax_delete_animal', function()
{
global $wpdb;
$table = $wpdb->prefix . 'tierdaten';
$wpdb->delete( $table, array( 'id' => $_POST['id'] ) );
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: ' . date('r'));
echo trim( json_encode(['success' => true]) );
wp_die();
});
Fancybox - 如果有人点击了删除按钮:
function showFancyBoxDelete($animal_id) {
// Get the modal
var animal_id = $animal_id;
var modal = document.getElementById('FancyBoxDelete');
// Get the button that opens the modal
var btn = document.getElementById("TestDelete");
//var myBtns = document.getElementsByClassName("btn_delete");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// Button Abbrechen
var abbrechendelete = document.getElementsByClassName("abbrechendelete");
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
document.getElementById("InhaltDelete").innerHTML = "<h2>Tierdaten löschen</h2><p>Möchten Sie wirklich den Datensatz mit der ID " + animal_id + " entgültig löschen?</p>";
document.getElementById("InhaltDeleteButtons").innerHTML = "<div class='btn_left'><input class='button-primary' onclick='closeFancyBox()' class='abbrechendelete' name='abbrechen' value='Abbrechen'></div><div style='padding-right:60%' class='btn_right'><input class='delete' type='button' value='Daten löschen'></div><div class='clear_div'></div>";
}
// auf Abbrechen klicken
abbrechendelete.onclick = function() {
modal.style.display = "none";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
jQuery(document).on('click', '.delete', function () {
var id = animal_id;
jQuery.ajax({
type: 'POST',
dataType : 'json',
url: ajaxurl,
data: {
action: 'delete_animal',
id: id
},
statusCode: {
'404': function() {
alert( "page not found" );
}
},
success: function (data) {
console.log(data);
if(data.type == "success") {
location.href = location.href;
}
else {
alert("Dein Eintrag konnte nicht gelöscht werden. ")
}
}
});
});
}