我花了很多小时才弄到这个。。。以及尝试和错误。因此,我通过一个示例(从开始)分享了如何在wordpress中使用ajaxhttps://www.tweaking4all.com/web-development/wordpress/wordpress-ajax-example/#comment-562814 并改编了示例)
--使用chrome开发者工具,并从网络标签中删除缓存——如果您遇到任何错误,请查看控制台,第一个目标是访问控制台;准备好了"E;当你点击按钮,如果一切正常,你也会得到一些不错的输出!
--作为自定义html块添加到wordpress网站:
<div id="receiving_div_id">
<p>Nothing loaded yet</p>
</div>
<button id="button_to_load_data">Get Ajax Content</button>
--添加到主题/js/按钮。js(创建js文件夹):
jQuery("#button_to_load_data").click(function() {
console.log( "ready!" );
var data = {
\'action\' : \'t4a_ajax_call\', // the name of your PHP function!
\'function\' : \'show_files\', // a random value we\'d like to pass
\'fileid\' : \'7\' // another random value we\'d like to pass
};
jQuery.post(my_ajax_object.ajax_url, data, function(response) {
jQuery("#receiving_div_id").html(response);
});
});
--添加到主题函数。php:
/* custom script in theme functions.php */
/* read button.js (->my-script) and localize admin-ajax.php for my-script */
function add_my_script() {
wp_enqueue_script( \'my-script\',
get_template_directory_uri() . \'/js/button.js\',
array ( \'jquery\' ),
false,
true
);
wp_localize_script( \'my-script\', \'my_ajax_object\',
array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'add_my_script\' );
/*ajax result */
add_action(\'wp_ajax_t4a_ajax_call\', \'t4a_ajax_call\'); // for logged in users only
add_action(\'wp_ajax_nopriv_t4a_ajax_call\', \'t4a_ajax_call\'); // for ALL users
function t4a_ajax_call(){
echo \'Ajax call output:\';
echo \'<pre>\';
var_dump($_POST);
echo \'</pre>\';
wp_die();// this is required to terminate immediately and return a proper response
}