最合适的回答,由SO网友:Kevin Langley Jr. 整理而成
这样做真的不是最好的做法。事实上,您不需要创建ajax。php文件,除非您打算将其包含在函数中。php文件。您需要阅读WordPress中的AJAX。您只需在“wp\\u ajax\\u name\\u of\\u action”上添加一个操作,并在javascript ajax函数中指定该操作即可。
WordPress编解码器的简单示例:
<?php
add_action(\'admin_head\', \'my_action_javascript\');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: \'my_action\',
whatever: 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert(\'Got this from the server: \' + response);
});
});
</script>
<?php
}
add_action(\'wp_ajax_my_action\', \'my_action_callback\');
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST[\'whatever\'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}