使用WP Rest API Ajax POST更新页面内容的问题求助
问题分析与解决方案
你的核心问题集中在这几点:
- 端点回调仅读取模板的原始文本,未执行其中的PHP代码,导致返回未解析的PHP内容而非渲染后的HTML
- Nonce存在拼写错误,可能导致权限验证失效
- 模板缺少产品循环的HTML输出逻辑
- 直接使用
$_POST获取参数不符合WP Rest API规范
以下是分步修正方案:
1. 修正Rest API端点回调函数
将读取文件改为执行模板并捕获渲染后的HTML,同时改用WP Rest API标准的参数获取方式:
function restAPI_endpoint_callback(WP_REST_Request $request) { // 验证Nonce(可选但推荐) if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) { return new WP_REST_Response('权限验证失败', 403); } // 获取showMore参数,默认值设为10 $perPage = (int)$request->get_param('showMore') ?: 10; // 开启输出缓冲,捕获模板渲染的HTML内容 ob_start(); // 传递参数到模板文件 set_query_var('per_page', $perPage); // 加载并执行模板 get_template_part('templates/more-products'); $htmlContent = ob_get_clean(); return new WP_REST_Response($htmlContent, 200); }
2. 完善模板文件(more-products.php)
添加产品循环的HTML输出逻辑,确保查询到的产品能渲染为前端可识别的HTML:
<?php $published_posts = wp_count_posts('product')->publish; $perPage = get_query_var('per_page') ?: 10; $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => $perPage, ); $products = new WP_Query($args); if ($products->have_posts()) : while ($products->have_posts()) : $products->the_post(); // 替换为你的产品HTML结构,示例如下: ?> <div class="product-card"> <h4><?php the_title(); ?></h4> <?php if (has_post_thumbnail()) : ?> <div class="product-thumb"><?php the_post_thumbnail('medium'); ?></div> <?php endif; ?> <p><?php the_excerpt(); ?></p> </div> <?php endwhile; wp_reset_postdata(); else : echo '<p>暂无更多产品</p>'; endif; ?>
3. 修正jQuery Ajax代码的错误
- 修正Nonce拼写(
restNounce→restNonce) - 修正请求头名称(
X-WP-Nounce→X-WP-Nonce)
$(document).on("click", '.js-show-more', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: myObj.restURL + 'baseURL/v1/baseEndPoint/endPoint', beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', myObj.restNonce); }, data: { showMore: productCount, }, success: function (response) { if (response) { console.log(response); $('.js-more-products').html(response); } }, error: function(xhr) { console.error('请求失败:', xhr.responseText); } }); });
额外优化建议
- 端点路由尽量语义化,比如改为
/custom/v1/products/load-more - 可添加
page分页参数,实现真正的无限滚动,而非一次性加载指定数量 - 对
productCount做合法性校验,避免传入过大数值影响性能
内容的提问来源于stack exchange,提问作者in2d
相关产品推荐
相关产品推荐

