我有一個WordPress網站,我將其配置爲使用jQuery/AJAX來查詢和加載div框內的帖子。WP AJAX:nonce在註銷時工作,但在登錄時不工作
下面是我在functions.php
(大量簡化,自然):
function mysite_enqueue_scripts() {
wp_register_script('mysite_front' , get_bloginfo('template_url') . '/js/front.js' , array('jquery'));
wp_enqueue_script('mysite_front'); //loads the front-side jquery
wp_localize_script('mysite_front' , 'AJAX' , array(
'ajaxurl' => admin_url('admin-ajax.php') ,
'nonce' => wp_create_nonce('mysite-ajax-nonce')
)); //localizes the script
}
add_action('wp_enqueue_scripts' , 'mysite_enqueue_scripts' , 100);
add_action('wp_ajax_nopriv_load_items' , 'mysite_ajax_load_items');
add_action('wp_ajax_load_items' , 'mysite_ajax_load_items');
function mysite_ajax_load_items() {
if(!check_ajax_referer('mysite-ajax-nonce' , 'nonce' , false)) {
wp_send_json(array('error' => 'nonce error'));
return;
} else {
[[[all the WP query stuff goes here and creates an $html string]]]
wp_send_json(array('html' => $html));
}
}
jQuery的front.js
:
jQuery(document).ready(function($) {
$('#mysite-load').click(function() {
var postData = {
action : 'load_items' ,
nonce : AJAX.nonce
};
jQuery.post(
AJAX.ajaxurl , postData , function(response) {
if(typeof(response['html']) !== 'undefined') {
$('#mysite-load').html(response['html']);
} else if(typeof(response['error']) !== 'undefined') {
$('#mysite-load').html('Error: ' + response['error']);
}
}
);
});
});
的HTML:
<div id="mysite-load">click</div>
當我不在登錄到該網站的wp-admin並加載此頁面,一切正常。
但是,當我登錄到該網站的wp-admin並加載此頁面時,它將返回'nonce error'
錯誤,而不是它應該加載的HTML。
該問題不是瀏覽器特定的;嘗試在Safari和Chrome中都收到相同的錯誤。我也嘗試使用wp_verify_nonce()
而不是check_ajax_referer()
,並且收到了相同的結果。
任何想法爲什麼會發生這種情況?