当我点击激活AJAX的按钮时,它会将我引导至admin-ajax.php页面,然后执行php函数。我正在努力寻找一种方法让它发挥作用。
PHP:
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "flag-post", WP_PLUGIN_URL.'/wp-flag-post/flag-post.js', array('jquery') );
wp_localize_script( 'flag-post', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'flag-post' );
}
function flag_post() {
do some stuff
die();
}
add_action('wp_ajax_flag_post', 'flag_post');
add_action('wp_ajax_nopriv_flag_post', 'flag_post');
$nonce = wp_create_nonce("flag_post_nonce");
$link = admin_url('admin-ajax.php?action=flag_post&post_id='.$post->ID.'&nonce='.$nonce);
echo '<a class="flag_post" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">vote for this article</a>';
javascript:
> jQuery(document).ready( function() {
>
> jQuery(".flag_post").click( function() {
> post_id = jQuery(this).attr("data-post_id")
> nonce = jQuery(this).attr("data-nonce")
>
> jQuery.ajax({
> type : "post",
> dataType : "json",
> url : myAjax.ajaxurl,
> data : {action: "flag_post"},
> success: function(response) {
> if(response.type == "success") {
> jQuery("#post_flagged").html("hello")
> alert("Yweeeeeee")
> }
> else {
> alert("Your vote could not be added")
> }
> }
> })
>
> })
>
> })