wordpress:check_ajax_referer方法验证ajax请求
class my_ajax { static $wpnonce = 'hello'; public function __construct () { add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts')); add_action('wp_ajax_nopriv_foo', array($this, 'foo')); add_action('wp_ajax_foo', array($this, 'foo')); } /**/ public function enqueue_scripts () { wp_enqueue_script('ajax', get_template_directory_uri() . '/assets/js/ajax.js', array('jquery'), false, true); /*ajax*/ wp_localize_script('ajax', 'ajax_vars', array( 'ajax_url' => admin_url('admin-ajax.php'), 'noce' => wp_create_nonce(self::$wpnonce), )); } /**/ public function foo () { if (! check_ajax_referer(self::$wpnonce, 'noce', false) ) { wp_send_json_error('Invalid Request'); } wp_send_json_success('You may pass an array...'); } } new my_ajax();
总结
两个核心的函数
注意:一个帐号