wordpress:check_ajax_referer方法验证ajax请求

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();
jQuery.ajax({
  url: ajax_vars.ajax_url,
  type: 'post',
  dataType: 'json',
  data: {
    action: 'foo',
    noce: ajax_vars.noce,
  },
  success: function($res) {
    if (!$res.success) {
      console.log($res.data);
    } else {
      console.log($res);
    }
  },
  error: function(xhr, error, status) {
    console.log(error, status);
  }
});

总结

两个核心的函数

wp_create_nonce( 'hello' ); // 创建回话的加密令牌
check_ajax_referer( 'hello', 'noce', false ); // 验证Ajax 请求

注意:一个帐号

评论
:broken_heart: :confounded: :flushed: :frowning: :grinning: :heart: :kissing_heart: :mask: :pensive: :rage: :relaxed: :scream: :smile: :smirk: :sob: :stuck_out_tongue_closed_eyes: :stuck_out_tongue_winking_eye: :wink: