2012-04-18 105 views
1

我正在使用wordpress ajax调用来从wordpress主题functions.php中的函数返回简单的内容。但是,将返回完整的html页面。WordPress的Ajax从functions.php返回完整的HTML页面,而不是回声

这里是Ajax调用

<?php 
$ajax_nonce = wp_create_nonce("iwhq_beginner_select_course"); 
?> 

<script type="text/javascript" language="javascript"> 
jQuery(document).ready(function(){ 

jQuery("#beg_golf_course").change(function() { //do this when course changes 

//in Wordpress ajaxurl always points to admin-ajax.php 
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; 
var course_id = 4; 

//Do the ajax 
    jQuery.ajax({ 
     type: "POST", 
     url: ajaxurl, 

     //NOTE - the action parameter calls the function in functions.php 
     data: { action: 'select_course_aj', course_id: course_id, _ajax_nonce: '<?php echo $ajax_nonce; ?>' }, 


     //display alert on success 
     success: function(html){ 
      alert(html); 
     } 
    }); //close jQuery.ajax(
    return false; 

    }); 
}); 
</script> 

这是

function select_course_func(){ 
echo $_POST["course_id"]; 
die(); 
} 

add_action('wp_ajax_select_course_aj','select_course_func'); 

包含了jQuery AJAX调用页面的HTML实际上是显示在警报,而不是在functions.php中的作用回声。

任何天才都能告诉我为什么?

感谢 马克

+0

我在函数.php中包含了select_course_func PHP调用中的nonce调用,但得到了相同的结果。 check_ajax_referer('iwhq_beginner_select_course','_ajax_nonce'); – Markol 2012-04-18 20:43:02

+0

你看过Firebug中的请求/响应了吗? – 2012-04-18 20:46:24

+0

那么究竟是什么提醒?你期待'4'是否正确?最新发生的是你在加载和html 404页面上使用html函数的div吗?检查您发送ajax呼叫的网址。像杰伊布兰查德说,你可以很容易地做到这一点在萤火虫或镀铬网络标签。 – Rooster 2012-04-18 21:35:05

回答

4

OK,问题解决了。看到我上面的最后3条评论加上...

!defined('DOING_AJAX')是一个常量,可以用来测试用户没有执行ajax请求。我将其与我的逻辑相结合,将非管理员重定向到前端,现在可以工作。

/* check the role of current loged in user for redirection */ 
add_action('admin_init','rt_checkRole'); 
function rt_checkRole() { 

    global $wp_roles; 
    $currentrole =''; 
    foreach ($wp_roles->role_names as $role => $name) { 
     if (current_user_can($role)){ 
        $currentrole = $role; 
       } 
     } 
     if(!defined('DOING_AJAX') && (!$currentrole || ($currentrole != 'administrator' && $currentrole != 'editor'))){ 
      wp_redirect (site_url().'/front-end-login/'); 
     } 
} 

https://wordpress.stackexchange.com/questions/26100/redirect-out-of-wp-admin-without-losing-admin-ajax-php

感谢所有评论谁发现了!定义( 'DOING_AJAX')。

+0

但是为什么所有的HTML都是原来的? – 2013-01-29 17:56:28

+0

我添加了哪个文件? – RenegadeAndy 2014-11-18 16:48:03

0

如果你想要做的Ajax调用非管理员用户,你应该使用下面的代码,这将禁止非管理员用户可湿性粉剂管理员的访问,但允许AJAX调用为每一位用户,登录或注销用户

function my_admin_init(){ 
    if(!defined('DOING_AJAX') && !current_user_can('administrator')){ 
     wp_redirect(home_url()); 
     exit(); 
    } 
} 
add_action('admin_init','my_admin_init'); 
相关问题