每当单击模式显示内容的按钮时尝试更新 url,设法找到如何更改它,但它返回 http://localhost:3000/wp-admin/admin-ajax.php
这不是我想要的,我想要在我的域名之后有正常的博客文章标题,有什么方法可以动态实现这一点吗?我正在使用 wordpress 来实现此目的。
window.history.pushState(null, null, this.url);
整个ajax.js
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
$('#postModal h5#postModalLabel').text(response.title);
$('#postModal .modal-body').html(response.content);
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
postModal.show();
window.history.pushState(null, null, this.url);
});
});
});
找到解决方案,因此您必须像这样在回调函数中存储 slug 名称。
// Get the post ID or some way to retrieve the post slug
$post_id = get_the_ID(); // Example: Assuming you're inside a loop
// Get the post slug
$post_slug = get_post_field('post_name', $post_id);
$arr_response = array(
'title' => get_the_title(),
'content' => get_the_content(),
'post_slug' => $post_slug,
);
echo json_encode($arr_response);
在ajax js文件中,您可以提取post_slug并将其存储在变量中
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
var postSlug = response.post_slug;
window.history.pushState(null, null, postSlug);