ajax - Wordpress:从帖子ID(ajax)返回页面的HTML
问题描述
我按照这个答案的说明进行操作:https ://stackoverflow.com/a/26950030/9200273
我能够根据传入的帖子 ID 从 Ajax 模板返回数据。
这就是模板的样子(与我发布的答案基本相同):
<?php
/*
Template Name: Ajax
*/
$post = get_post($_POST['id']);
if ($post) {
setup_postdata($post); ?>
<div><?php the_title();?></div>
<?php }
因此,当我单击链接时,我的 ajax 逻辑将用返回的内容替换 div 中的内容。在这种情况下,只是帖子/页面的标题。
如果我不使用 ajax,如何返回页面内容?喜欢我的自定义页面模板及其内容。
我的 JS:
$(document).on( 'click', '.nav-header a', function( e ) {
e.preventDefault();
$.ajaxSetup({cache:false});
pageurl = $(this).attr('href');
if( pageurl != window.location ) {
window.history.pushState( {path: pageurl}, '', pageurl);
}
if ( $(this).parent().attr('class') != "logo" ) {
var postID = $(this).parent().attr("class").split('page-item-').pop().split(' ')[0];
} else {
var postID = $(this).attr("class").split('page-item-').pop().split(' ')[0];
}
$.ajax({
url: wp_vars.httpHost,
type: "POST",
data: {
id: postID
},
beforeSend: function() {
$("main.main-wrap").children().remove();
},
success: function (data) {
$("main.main-wrap").append($(data));
console.log(data);
},
error: function () {
console.log(data);
}
});
});
});
解决方案
要在将帖子类保存到 $post 变量时获取帖子内容,请使用它。
<?php echo $post->post_content; ?>
推荐阅读
- c++ - 64 位系统上的 C++ SQL Server 连接
- mysql - 建立sql事务关联表时出现null问题
- azure - Azure 容器 - 无法登录私有注册表“从 docker 注册表收到错误响应”
- java - 有没有办法让 Spring-Boot 显示有关“BeanCreationException:创建带有名称的 bean 时出错”的更多信息?
- c - 为什么我的 DFSDM 寄存器位在我的 STM32L476 上没有改变?
- laravel - 如何在 Laravel 中获取父类别的所有子类别?
- python - 优化在数据框中查找行对
- d3.js - 为什么水平线在堆栈条形图中无法正常工作
- arrays - 在 numpy 数组中使用带有切片的方程 Pythopn
- angular - Angular - 已被 CORS 策略阻止 - 标头 - 不允许请求标头字段身份验证