【发布时间】: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