【问题标题】:Wordpress load sidebar.php with Ajax - loads wrong content (index.php instead)Wordpress 使用 Ajax 加载 sidebar.php - 加载错误的内容(改为 index.php)
【发布时间】:2014-11-07 08:50:43
【问题描述】:

我几乎要用 Ajax 在 wordpress 中加载侧边栏,使用这个例子 (https://wordpress.stackexchange.com/questions/61830/use-ajax-request-to-load-sidebar)

但它不会加载我的新 sidebar-ajax.php,而是始终将 index.php 加载到名为“sidebar”的 div 中。 我有感觉,我的函数 (get_template_part('sidebar-ajax'); ) 没有正确执行,但是找不到错误

在我的functions.php中我插入了:

add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
function theme_enqueue_scripts() {
wp_enqueue_script('jquery');
/* load your js file in footer */
wp_enqueue_script('theme-script', get_stylesheet_directory_uri() . '/your-js-file.js',   
false, false, true);
}

add_action('wp_ajax_get_ajax_sidebar', 'check_ajax');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax');
function check_ajax() {
?>
get_template_part('sidebar-ajax');
<?php
} ?>

我的 js。文件:

jQuery.ajax({
type: 'POST',
url: location.href,
data: { get_ajax_sidebar: 1 },
success: function(data){
    jQuery('#sidebar').html(data);
}
});

在我的 index.php 中我添加了:

<div id="sidebar"></div>

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 当页面加载/触发函数时“location.href”里面是什么?
  • 我不太明白这个问题 - 抱歉,我是 JavaScript 的初学者 - 我猜是 index.php ?
  • 在您的 ajax 调用之前尝试 console.log(location.href)。您可以在控制台中看到输出,例如萤火虫。现在您可以检查它是否是应该调用的 url

标签: javascript php jquery ajax wordpress


【解决方案1】:

get_template_part() 在 php 标签之外...为什么?我喜欢使用get_sidebar()。试试这个:

add_action( 'wp_ajax_get_ajax_sidebar', 'check_ajax' );
add_action( 'wp_ajax_nopriv_get_ajax_sidebar', 'check_ajax' );
function check_ajax() {
    get_sidebar( 'ajax' );
}

【讨论】:

  • 这是真的,但在原始代码中是相同的 - 演示(见链接),在另一个线程上它说它正在工作......所以我假设我复制/粘贴我的网站使用相同的代码
  • 如果您实际上没有在 php 中调用该函数,您将无法使用它。您必须摆脱 get_template_part('sidebar-ajax'); 周围的 php 标签
  • 好的,我做到了。还是行不通。您可以查看 www.shopmajorbrands.com/ajax/
  • 我认为您的页面中有更多错误,例如 your-jsc-file.js 上的 404,如果这是保存您的 jquery 的文件,那么它将无法正常工作。
  • 所以最后这是正确的,因为您需要删除 php 标签并修复脚本的排队问题......如果是这样,请将其标记为正确答案。
【解决方案2】:

聚会有点晚了,但是这不起作用的原因是您需要正确的 url 来调用 ajax 函数。在 wordpress 的后端,这是自动完成的,并在名为 ajaxurl 的 javascript 变量中定义。在前端,您必须自己定义它,这非常简单。在你的functions.php中:

add_action('wp_head','yourfunctionname_ajaxurl');
function yourfunctionname_ajaxurl() {
    ?>
    <script type="text/javascript">
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
    <?php
}

现在您可以将 javascript 代码更改为:

jQuery.ajax({
    type: 'POST',
    url: ajaxurl,
    data: { action:'get_ajax_sidebar' },
    success: function(data){
        jQuery('#sidebar').html(data);
    }
});

更多信息可以在这里找到法典:wp_ajax

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多