admin-ajax.php
负载wp-load.php
:
/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . \'/wp-load.php\' );
wp-load.php
负载
wp-config.php
, 还有那里
wp-settings.php
已加载。
在这里我们发现:
// Load the functions for the active theme, for both parent and child theme if applicable.
if ( ! defined( \'WP_INSTALLING\' ) || \'wp-activate.php\' === $pagenow ) {
if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . \'/functions.php\' ) )
include( STYLESHEETPATH . \'/functions.php\' );
if ( file_exists( TEMPLATEPATH . \'/functions.php\' ) )
include( TEMPLATEPATH . \'/functions.php\' );
}
所以,是的,主题是
functions.php
已加载。
中有一个例外wp-settings.php
:
// Stop most of WordPress from being loaded if we just want the basics.
if ( SHORTINIT )
return false;
何时
SHORTINIT
定义为
TRUE
之前,将不会加载主题。
所以检查一下SHORTINIT
是TRUE
出于某种原因。
另一个常见错误是is_admin()
. 这总是TRUE
在里面admin-ajax.php
, 因此,以下操作将失败:
if ( ! is_admin() )
// register or execute AJAX stuff
调试AJAX有一种最简单有效的方法是使用HTTP头调试AJAX。
下面是一个简单的助手函数:
function send_debug_header( $msg )
{
static $counter = 1;
header( "X-Debug-Ajax-$counter: $msg" );
$counter += 1;
}
这个插件展示了如何使用它:
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: Debug AJAX per HTTP
* Description: Look at the HTTP headers in your browser\'s network console
*/
// The constant is already defined when plugins are loaded.
// Prove we have been called.
if ( defined( \'DOING_AJAX\' ) && DOING_AJAX )
send_debug_header( \'File "\' . __FILE__ . \'" was called on an AJAX request.\' );
function send_debug_header( $msg )
{
static $counter = 1;
header( "X-Debug-Ajax-$counter: $msg" );
$counter += 1;
}
add_action( \'wp_ajax_debug_test\', \'t5_debug_test\' );
add_action( \'wp_ajax_nopriv_debug_test\', \'t5_debug_test\' );
function t5_debug_test()
{
$in = is_user_logged_in() ? \'\' : \'not \';
send_debug_header( \'Function "\' . __FUNCTION__ . \'" was called and the user is \' . $in . \'logged in.\' );
print_r( debug_backtrace() );
die(1);
}
add_action( \'wp_enqueue_scripts\', \'t5_enqueue_jquery\' );
function t5_enqueue_jquery()
{
wp_enqueue_script( \'jquery\' );
}
add_action( \'wp_footer\', \'t5_debug_ajax_test_button\', 0 );
function t5_debug_ajax_test_button()
{
?>
<input type="submit" id="t5debugajax" value="Debug AJAX">
<script>
jQuery( function($){
var sendFeedBack = function( response ){
console.log( response );
};
$("#t5debugajax").on("click", function(){
$.post(
"<?php echo admin_url( \'admin-ajax.php\' ); ?>",
{
action: "debug_test"
},
sendFeedBack
);
});
});
</script>
<?php
}
它将在前端添加一个按钮,单击该按钮时会触发AJAX请求。打开浏览器的网络控制台,查看请求的响应标头: