我想你的问题是ajaxurl
对于您的脚本不可用。在加载js代码之前,尝试定义该变量。最好的方法是使用wp\\u localize\\u脚本:
PHP:
add_action( \'wp_enqueue_scripts\', \'cyb_enqueue_scripts\' );
function cyb_enqueue_scripts() {
//Change the key and url with yours
wp_register_script(\'my-js\', get_stylesheet_directory_uri(). \'/js/my-js.js\', array( \'jquery\' ) );
wp_enqueue_script(\'my-js\');
//Localize script data to be used in my-js.js
$scriptData = array();
$scriptData[\'ajaxurl\'] = admin_url( \'admin-ajax.php\' );
$scriptData[\'action\'] = \'voteIncrement\';
wp_localize_script( \'my-js\', \'my_js_data\', $scriptData );
}
add_action("wp_ajax_voteIncrement", "voteIncrement");
add_action("wp_ajax_nopriv_voteIncrement", "voteIncrement");
function voteIncrement(){
echo \'hello\';
die();
}
js:
(function($){
$(document).ready(function(){
$(\'.btn-vote\').on(\'click\',function(e){
e.preventDefault();
var $that = jQuery(this);
var id = $that.attr(\'data-id\');
var data = {
\'action\': my_js_data.action,
\'id\': id
};
jQuery.post( my_js_data.ajaxurl, data, function(response) {
console.log(response);
$that.find(\'.vote-count\').html(response);
});
});
});
})(jQuery);
此外,我还将更改get的ajax请求中的post方法。它比post更快,您的案例似乎不需要post请求。