Answers:
“更安全,更清洁”的方式是使用wordpress和wp_ajax
hook 附带的admin-ajax.php 从插件文件中调用处理函数,并使用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 POST中的操作值匹配。
然后在您的函数中只需确保请求来自有效来源
function my_AJAX_processing_function(){
check_ajax_referer('my_ajax_nonce');
//do stuff here...
}
希望这可以帮助