See documentation
WordPress拥有管理ajax。wp includes/folder中的php文件。输入数据参数
action
并创建挂钩:
add_action(\'wp_ajax_{your_action}\', \'handler\');
add_action(\'wp_ajax_nopriv_{your_action}\', \'handler\');
ajax。url参数可以通过使用
wp_localize_script(\'YOUR SCRIPT handle\', \'ajax\', array(\'url\'=> admin_url(\'admin-ajax.php\')))
所有代码必须如下所示:
add_action( \'wp_enqueue_scripts\', \'callback_for_setting_up_scripts\' );
function callback_for_setting_up_scripts() {
wp_register_style( \'mein-plugin\', plugins_url( \'style.css\', __FILE__ ) );
wp_enqueue_style( \'mein-plugin\' );
wp_enqueue_script( \'ajax-sender\', plugins_url( \'ajax-sender.js\', __FILE__ ), array( \'jquery\' ), null, true );
wp_localize_script( \'ajax-sender\', \'ajax\', array(
\'url\' => admin_url( \'admin-ajax.php\' ),
\'nonce\' => wp_create_nonce( \'my_nonce\' ),
) );
}
Javascript文件:
jQuery(function () {
jQuery(\'#inp\').keyup(function () {
var inpval = jQuery(\'#inp\').val();
jQuery.ajax({
type: \'POST\',
data: {
action: \'simple_wordpress_ajax\',
nonce: ajax.my_nonce,
p: inpval
},
url: ajax.url,
success: function (data) {
jQuery(\'.results\').html(data.html);
}
});
});
});
和在php文件中
add_action(\'wp_ajax_simple_wordpress_ajax\', \'simple_ajax_handler\');
add_action(\'wp_ajax_nopriv_simple_wordpress_ajax\', \'simple_ajax_handler\');
function simple-wordpress-ajax(){
check_ajax_referer(\'my_nonce\', \'nonce\', true);
// your php code
$return = array(\'html\' => \'test\'); // your data for return
wp_send_json_success($return);
}
像这样的。