這是我第一次實現ajax。我一直在苦苦尋找這個Ajax代碼幾天,在stackoverflow中搜索,閱讀博客,嘗試了很多不同的解決方案,甚至發現了一些錯誤,但是..代碼仍然返回$ response = Undefined/0。Add_action鉤子未觸發,所以Ajax返回undefined
Wordpress在頁面中上傳ajax,頁面與服務器通過ajax調用交互並返回成功,但變量$ response不傳遞給jquery,既不是response.status也不是response.message。
實際上,在Firefox控制檯中,$ response是Undefined或0。
**所有這些檢查後,我發佈了這個問題。 Snake_Eyes和Froxz發現了一些我糾正的錯誤。不過,對於$ response,ajax仍然返回Undefined。
我調查了Wordpress是否調用do_stuff_pp()。 爲此,我使用PHP函數error_log()逐行檢查了do_stuff_pp()函數。分析顯示do_stuff_pp()函數從不運行。但我不知道爲什麼::(**
我使用jQuery 1.5.1,2.9.2 WP和PHP 5.2.6
function my_init() {
switch ($page_num) {
case 4445: // enrollment page1
$path = get_bloginfo('template_directory');
$source = $path . "/js/ajax_test.js";
wp_enqueue_script(
$handle='this-is-my-ajax-handle',
$source,
$dependencies = array('jquery')
);
break;
}
switch ($page_num) {
case 4445: // enrollment page1
$data = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajaxin_it'),
'action' => 'ajaxin_it'
);
wp_localize_script('this-is-my-ajax-handle','ajaxYall', $data);
break;
}
}
add_action('init', 'my_init');
// Define functions for ajax:
$my_action = 'ajaxin_it';
if (defined('DOING-AJAX') && DOING_AJAX) {
// for loggedin users
add_action('wp_ajax_' . $my_action, 'do_stuff_pp');
// for non logged in users
add_action('wp_ajax_nopriv_' . $my_action, 'do_stuff_pp');
}
function do_stuff_pp(){
$response = array(
'status' => 'error',
'message' => "It's AJAX Y'all!"
);
// check is a legitimate call
if(isset($_GET['nonce']) && wp_verify_nonce($_GET['nonce'], 'ajaxin_it')){
$response = array(
'status' => 'success',
'message' => "It's AJAX Y'all!"
);
}
header('Content: application/json');
echo json_encode($response);
die();
}
這是.js文件:
jQuery(document).ready(function($){
$('#text_ajax_yall').click(function(){
var $el = $(this);
alert(ajaxYall.nonce);
$.ajax({url:ajaxYall.ajaxurl,action:ajaxYall.action,nonce:ajaxYall.nonce,type:'GET',dataType:'json',success:function(response, textStatus, jqXHR){
if(200 == jqXHR.status && 'success' == textStatus) {
if('success' == response.status){
$el.after('<p style="color:green;">' + response.message+ '</p>');
} else {
$el.after('<p style="color:red;">' + response.message + '</p>');
}
}
// $el.after('<p style="color:green;">' + response.message + '</p>');
console.log(response.message, textStatus, jqXHR);
}});
});
});
這樣做有什麼具體原因以及如何解決?
我使用PHP 5.2.6。 – user1232551