下面是我在Wordpress中用于AJAX的基本设置。而不是加载wp负载。php;只需对AJAX调用使用Wordpress默认方法。这还允许您通过开关过滤Javascript中的函数调用。我还为wp\\u localize\\u脚本添加了一个快速示例。
<?php
add_action(\'wp_enqueue_scripts\', \'YOUR_NAME_scripts\'); //back end
function YOUR_NAME_scripts( $hook_suffix ) {
wp_enqueue_script(\'YOUR_NAME-js\');
global $blog_id;
$params = array(
\'site_url\' => site_url(),
\'admin_ajax_url\' => site_url() . \'/wp-admin/admin-ajax.php\'
);
wp_localize_script( \'jquery\', \'YOUR_NAME\', $params );
}
add_action(\'wp_ajax_nopriv_YOUR_NAME_ajax\', \'YOUR_NAME_ajax_function\');
add_action(\'wp_ajax_YOUR_NAME_ajax\', \'YOUR_NAME_ajax_function\');
function YOUR_NAME_ajax_function(){
fobu_load_classes();
switch($_REQUEST[\'fn\']):
case \'test_ajax\':
$output = $_REQUEST[\'data\'];
break;
default:
$output = \'No function specified, check your jQuery.ajax() call\';
break;
endswitch;
ob_clean();
$output=json_encode($output);
if( is_array( $output ) ):
print_r( $output );
else:
echo $output;
endif;
die();
}
?>
<script>
//in YOUR_NAME.js or whatever
jQuery(document).ready(function() {
(function ($) {
jQuery.ajax({
url: YOUR_NAME.admin_ajax_url,
dataType: \'json\',
//type:\'POST\',
data: {
\'action\':\'YOUR_NAME_ajax\',
\'fn\': \'test_ajax\',
\'data\': data
},
success: function(results){
//console.log(results);
if( results ){
}
},// end of success
error: function(errorThrown){console.log(errorThrown);}
});// end of ajax
})(jQuery);
});
</script>