“更安全、更干净”的方法是使用管理ajax。wordpress和wp_ajax
钩子从插件文件调用处理函数,并使用wp nonce检查调用的完整性。
例如:
您的ajax JQuery调用将是
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: \'ACTION_NAME\',
Whatever: \'1234\',
_ajax_nonce: \'<?php echo wp_create_nonce( \'my_ajax_nonce\' ); ?>\'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
// If you need it on a public facing page, uncomment the following line:
// var ajaxurl = \'<?php echo admin_url(\'admin-ajax.php\'); ?>\';
jQuery.post(ajaxurl, data, function(response) {
alert(\'Got this from the server: \' + response);
});
});
</script>
然后在插件文件中添加
//if you want only logged in users to access this function use this hook
add_action(\'wp_ajax_ACTION_NAME\', \'my_AJAX_processing_function\');
//if you want none logged in users to access this function use this hook
add_action(\'wp_ajax_nopriv_ACTION_NAME\', \'my_AJAX_processing_function\');
*如果您希望登录的用户和来宾通过ajax访问您的功能,请添加这两个挂钩。
*ACTION_NAME 必须与ajax帖子中的动作值匹配。
然后在您的函数中,只需确保请求来自有效的源
function my_AJAX_processing_function(){
check_ajax_referer(\'my_ajax_nonce\');
//do stuff here...
}
希望这有帮助