問題描述
試圖找出一個程序員的問題。我想知道當您執行管理員端 AJAX 時 functions.php 文件是否被調用?我知道,當你做一個 AJAX 調用時,WP 的一部分被加載來處理該呼叫併發回一個響應。那是 functions.php 檔案嗎?
我問的原因是因為他正在使用 Meta-Box 插件的類,而是加載它作為主題的一部分。該類中有一些 AJAX 只返回空的響應,我認為它是因為處理響應的代碼不會被加載。當 WP 處理 AJAX 時,是否有任何文檔加載?
最佳解決方案
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()的錯誤使用。這是 admin-ajax.php 中的 TRUE,所以以下將失敗:
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 請求。打開瀏覽器的網絡控制枱並查看請求的響應標頭:
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
