【发布时间】:2021-03-19 10:22:54
【问题描述】:
目标:使用 AJAX 显示帖子标题和内容。
到目前为止我做了什么:
在functions.php中加载custom.js并本地化AJAX:
wp_enqueue_script( 'custom_js', get_stylesheet_directory_uri() . '/custom.js', array( 'jquery' ) );
wp_localize_script( 'custom_js', 'ajax_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
在functions.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="postdata">
<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>';
}
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );
在 custom.js 中做 AJAX 的东西:
jQuery(document).ready(function(){
jQuery.post(ajax_object.ajaxurl, {
action: 'my_load_ajax_content ',
post_id: 17521 // << should grab this from input...
}, function(data) {
var $response = jQuery(data);
var postdata = $response.filter('#postdata').html();
jQuery('.stickithere').html(postdata);
});
最后在页面上给它一个加载位置:
<div class="stickithere"></div>
我收到 400 错误,我不知道为什么,但我猜这与本地化 AJAX 有关,因为这似乎是我最近大部分噩梦的原因。
【问题讨论】:
-
错误信息告诉你什么?您尝试过什么来解决问题?
-
localising AJAX是什么意思?如果所有信息设置正确,您是否检查过网络选项卡?