在WordPress中进行AJAX调用时,您应该始终发布到admin-ajax.php
文件下面是你如何做到这一点。
在插件中或functions.php
:
function process_my_ajax_call() {
// Do your processing here (save to database etc.)
// All WP API functions are available for you here
}
// This will allow not logged in users to use the functionality
add_action( \'wp_admin_my_action_no_priv\', \'process_my_ajax_call\' );
// This will allow only logged in users to use the functionality
add_action( \'wp_admin_my_action\', \'process_my_ajax_call\' );
您还必须将正确的URL传递给
admin-ajax.php
文件到您的JavaScript和
wp_localize_script
功能非常强大,仅此而已:
function localize_my_scripts() {
$localizations = array(
\'ajaxUrl\' => admin_url( \'admin-ajax.php\' ),
);
wp_localize_script( \'my-script-handle\', \'myVars\', $localizations );
}
add_action( \'wp_enqueue_scripts\', \'localize_my_scripts\' );
现在在JavaScript中:
$.ajax({
url: myVars.ajaxUrl, // Notice the AJAX URL here!
type: \'post\',
data: \'username=test&action=my_action\', // Notice the action name here! This is the basis on which WP calls your process_my_ajax_call() function.
cache: false,
success: function ( response ) {
// Parse ajax response here
// Do something with the response
},
error: function ( response ) {
// Handle error response here
};
});
当然,这只是对如何在WordPress中进行AJAX调用的一个巨大总结。您仍然需要验证nonce,使用WP\\u AJAX\\u response类创建适当的AJAX响应,然后将WP AJAX响应脚本排入前端以处理WP的响应。如果你想了解更多,有一个
comprehensive guide to AJAX in WordPress written by Ronald Huereca 而且它是免费的!