繁体   English   中英

使用AJAX删除前端的WordPress帖子

[英]Deleting WordPress posts in front-end with AJAX

我试图使用AJAX从前端删除WordPress帖子。 我的代码删除帖子,但显示空白页面“成功”,当我想淡出这篇文章没有页面重新加载和显示空白页面。

PHP代码:

<?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 ?>

Functions.php代码:

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而不是成功

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM