【发布时间】:2016-08-18 12:04:54
【问题描述】:
我一直在尝试在此线程中实施@SaiveSEO 的建议: Proper way to load a single post via Ajax?
想法:单击按钮并通过 AJAX 加载帖子。想法是您将拥有一个按钮树,让人们可以快速导航到有用的内容。
不幸的是,它失败了。
在控制台中,我收到消息“ReferenceError: ajax_object is not defined”,它指的是“$.post(ajax_object.ajaxurl...”这一行
我做错了什么?
这是我的 HTML:
<button class="get_project" data-postid="3300">PROJECT NAME</button>
<div class="postcontainer"></div>
这是我的 Javascript:
jQuery(function($){
$('.get_project').click(function() {
var postid = $(this).data('postid'); // Amended by @dingo_d
$.post(ajax_object.ajaxurl, {
action: 'my_load_ajax_content ',
postid: postid
}, function(data) {
var $response = $(data);
var postdata = $response.filter('#postdata').html();
$('.postcontainer').html(postdata);
});
})
//alert( "hello world" );
});
这是我的functions.php文件中的php:
function my_load_ajax_content () {
$pid = intval($_POST['post_id']);
$the_query = new WP_Query(array('p' => $pid));
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$data = '
<div class="post-container">
<div id="project-content">
<h1 class="entry-title">'.get_the_title().'</h1>
<div class="entry-content">'.get_the_content().'</div>
</div>
</div>
';
}
}
else {
echo '<div id="postdata">'.__('Didnt find anything', THEME_NAME).'</div>';
}
wp_reset_postdata();
echo '<div id="postdata">'.$data.'</div>';
}
// Next two lines corrected - thanks @dingo_d
add_action ( 'wp_ajax_my_load_ajax_content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_nopriv_my_load_ajax_content', 'my_load_ajax_content' );
脚本入队函数中的functions.php中也需要:
wp_enqueue_script( 'myajaxpostloader', get_template_directory_uri().'/js/ajax.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'myajaxpostloader', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
(请注意,我的 Javascript 保存为 /js/ajax.js,其中 /js/ 是 Wordpress 主题的子目录)。
【问题讨论】: