我试图使用AJAX从前端删除wordpress帖子.
我的代码删除帖子,但显示空白页面“成功”,当我想淡出这篇文章没有页面重新加载和显示空白页面.
<?PHP if( current_user_can( 'delete_post' ) ) : ?>
<?PHP $nonce = wp_create_nonce('my_delete_post_nonce') ?>
<a href="<?PHP echo admin_url( 'admin-ajax.PHP?action=my_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?PHP the_ID() ?>" data-nonce="<?PHP echo $nonce ?>" class="delete-post">delete</a>
<?PHP endif ?>
function my_frontend_script() {
wp_enqueue_script( 'my_script', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_frontend_script' );
wp_localize_script( 'js/my_script.js', 'MyAjax2', array( 'ajaxurl' => admin_url( 'admin-ajax.PHP' ), 'ajaxnonce' => wp_create_nonce('ajax-nonce') ) );
add_action( 'wp_ajax_my_delete_post', 'my_delete_post' );
function my_delete_post(){
$permission = check_ajax_referer( 'my_delete_post_nonce', 'nonce', false );
if( $permission == false ) {
echo 'error';
}
else {
wp_delete_post( $_REQUEST['id'] );
echo 'success';
}
die();
}
my_script.js代码:
jQuery( document ).ready( function($) {
$(document).on( 'click', '.delete-post', function() {
var id = $(this).data('id');
var nonce = $(this).data('nonce');
var post = $(this).parents('.post:first');
$.ajax({
type: 'post',
url: MyAjax2.ajaxurl,
data: {
action: 'my_delete_post',
nonce: nonce,
id: id
},
success: function( result ) {
if( result == 'success7' ) {
post.fadeOut( function(){
post.remove();
});
}
}
})
return false;
})
})
问题是页面正在重新加载到带有“成功”文本的空白页面,当它应该淡出并从当前页面删除帖子,而不重新加载.
它看起来像my_script.js甚至根本没用:(
任何帮助非常感谢.
解决方法:
<a href="<?PHP echo admin_url( 'admin-ajax.PHP?action=my_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?PHP the_ID() ?>" data-nonce="<?PHP echo $nonce ?>" class="delete-post">delete</a>
它正在重新加载,因为它首先加载你的href属性中的url,然后执行你的ajax调用.那不是你想要的.你想只执行onclick.这应该可以解决问题.只需在你的href中放一个#
<a href=# data-id="<?PHP the_ID() ?>" data-nonce="<?PHP echo $nonce ?>" class="delete-post">delete</a>
或制作按钮
<button data-id="<?PHP the_ID() ?>" data-nonce="<?PHP echo $nonce ?>" class="delete-post">delete</button>
if( result == 'success7' )
成功7而不是成功
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。