繁体   English   中英

以管理员身份登录时,Wordpress Ajax 调用不起作用

[英]Wordpress Ajax call not working when logged in as an Admin

我正在尝试使 ajax 调用在 wordpress 中工作。 如果您已注销,则代码可以工作,但是在您登录的那一刻,代码将停止工作并引发错误。 那么谁能告诉我问题出在哪里?

错误 400(错误请求)

jquery.min.js:2 POST http://localhost/wp-ajax/wp-admin/admin-ajax.php 400 (Bad Request)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
S.<computed> @ jquery.min.js:2
fetch @ (index):98
onclick @ (index):107

功能。php

wp_enqueue_script( 
    'ajax-script',
     get_template_directory_uri() . '/assets/js/script.js', 
     array ( 'jquery' ), 
     1.1, 
     true
);

wp_localize_script(
    'ajax-script',
    'my_ajax_obj',
    array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
         'nonce'    => wp_create_nonce( 'title_example' ),
    )
);



add_action('wp-ajax_my_action', 'data_fetch');
add_action('wp_ajax_nopriv_my_action', 'data_fetch');
function data_fetch(){
    $the_query = new WP_Query(array('posts_per_page'=>10));
    if($the_query->have_posts()):
        while($the_query->have_posts()) : $the_query->the_post(); ?>
            <h2><?php the_title(); ?></h2>
            <p><i><?php the_excerpt(); ?></i></p><hr>
            <?php endwhile;
            wp_reset_postdata();
    endif;
    die();
}

index.php

<script type="text/javascript" src="wp-includes/js/jquery/jquery.min.js"></script>
<script>
function fetch() {
    // jQuery("#datafetch").html("<h2>"+my_ajax_obj.ajax_url+" </h2>");

    jQuery.post(my_ajax_obj.ajax_url, {'action': 'my_action'}, function(response) {
        jQuery('#datafetch').append(response);
    });

}

</script>

<div id="datafetch">
    <button onclick="fetch()">Įkelti įrašus</button>
</div>

add_action('wp-ajax_my_action', 'data_fetch'); wp-ajax更改为wp_ajax ;

暂无
暂无

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

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