ajax for visitors wordpress

时间:2014-02-20 作者:loopy

我有一段在WordPress中执行ajax的代码,它在管理页面中运行良好,但我希望它在我的主题主页中运行

  <?php
   add_action( \'admin_footer\', \'my_action_javascript\' );

 function my_action_javascript() {
    ?>

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

var data = {
    action: \'my_action\',
    whatever: 1234
};

                                                                                    // since 2.8 ajaxurl is always defined in the admin header and points to admin-      ajax.php
  $.post(ajaxurl, data, function(response) {
    alert(\'Got this from the server: \' + response);
    });
       });
    </script>
 <?php
    }

 add_action( \'wp_ajax_my_action\', \'my_action_callback\' );

 function my_action_callback() {
global $wpdb; // this is how you get access to the database

$whatever = intval( $_POST[\'whatever\'] );

$whatever += 10;

    echo $whatever;

die(); // this is required to return a proper result
    }


   add_action( \'wp_ajax_my_action\', \'my_action_callback\' );
   add_action( \'wp_ajax_nopriv_my_action\', \'my_action_callback\' );

1 个回复
SO网友:fischi

您还需要向非特权用户添加操作回调。它的工作方式与您注册my_action_callback - 您只需要再添加一行。

add_action( \'wp_ajax_my_action\', \'my_action_callback\' );
add_action( \'wp_ajax_nopriv_my_action\', \'my_action_callback\' );
请注意wp_ajax_nopriv_ 在您的操作之前-这告诉WordPress任何用户都可以调用此操作。,鉴于wp_ajax_ 仅允许登录用户运行脚本。

在正确格式化和清理代码之后,我看到了一些事情。

您添加了my_action_callback 两次到wp_ajax_my_action您使用的admin_footer 而不是wp_footer => 前端没有输出ajaxurl 未定义清理所有这些,您的版本就会运行良好:

function my_action_javascript() {
    ?>
    <script type="text/javascript" >
        var ajaxurl = \'<?php echo admin_url(\'admin-ajax.php\'); ?>\';
        jQuery(document).ready(function($) {
            var data = {
                action: \'my_action\',
                whatever: 1234
            };
            // since 2.8 ajaxurl is always defined in the admin header and points to admin-      ajax.php
            $.post(ajaxurl, data, function(response) {
                alert(\'Got this from the server: \' + response);
            });
        });
    </script>
    <?php
}

function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    $whatever = intval( $_POST[\'whatever\'] );
    $whatever += 10;
    echo $whatever;
    die(); // this is required to return a proper result
}


add_action( \'wp_ajax_my_action\', \'my_action_callback\' );
add_action( \'wp_ajax_nopriv_my_action\', \'my_action_callback\' );

结束