doupao2277 2012-04-18 20:41
浏览 137
已采纳

Wordpress Ajax从functions.php返回完整的html页面,而不是echo

I am using a wordpress ajax call to return simple content from a function in wordpress theme functions.php. However, a full html page is returned instead.

Here is the ajax call

<?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>

And this is the function in functions.php

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

add_action('wp_ajax_select_course_aj','select_course_func');

The HTML of the page containing the jquery ajax call is actually displayed in the alert instead of the echo.

Any geniuses out there able to tell me why?

Thanks Mark

  • 写回答

2条回答 默认 最新

  • dreljie602951 2012-04-19 14:24
    关注

    OK, Problem solved. See my last 3 comments above plus...

    !defined('DOING_AJAX') is a constant that can be used to test that the user is not performing an ajax request. I combined this with my logic for redirecting non-admins to the frontend and it works now.

    /* 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/');
            }
    }
    

    Found out about !defined('DOING_AJAX') at https://wordpress.stackexchange.com/questions/26100/redirect-out-of-wp-admin-without-losing-admin-ajax-php

    Thanks to all who commented.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?