POST请求下API向AJAX传值异常:仅返回部分数据求助
排查AJAX调用WP REST API返回内容缺失的问题
看起来你遇到的问题很典型——Postman测试正常,但前端AJAX调用时只有postID能正确显示,其他内容(标题、内容等)都缺失。结合你的代码,我来帮你分析原因并给出修复方案:
核心问题诊断
- REST API参数获取方式不规范:你在PHP中直接用
$_POST['post_id']获取参数,但WP REST API有自己的参数处理机制,直接依赖$_POST可能在某些上下文(比如AJAX请求的Content-Type处理)中出现隐性问题。 get_the_title()依赖全局上下文:这个函数需要WordPress的全局$post对象或当前查询环境支持,在REST API的回调函数中,这个环境可能没有被初始化,导致无法正确获取标题。- AJAX的
dataType设置不匹配:你指定了dataType: 'json',但API返回的是HTML字符串,这会让jQuery尝试把HTML解析成JSON,可能导致部分内容被截断或解析失败。
修复方案
1. 修正PHP端的参数获取与内容获取逻辑
改用WP REST API官方推荐的WP_REST_Request对象获取参数,同时替换get_the_title()为更可靠的get_post_field():
add_action( 'rest_api_init', function (){ register_rest_route( 'api', '/hotelRooms', array( 'methods' => 'POST', 'callback' => 'hotelRooms', // 可选:添加权限验证,确保请求合法 'permission_callback' => function() { return current_user_can('read'); } )); }); function hotelRooms(WP_REST_Request $request){ // 从请求对象获取参数,并强制转为整数,避免非法值 $postID = intval($request->get_param('post_id')); // 先验证文章是否存在 if (!get_post($postID)) { return new WP_Error('invalid_post', '无效的文章ID', array('status' => 404)); } // 用get_post_field直接获取字段,不依赖全局上下文 $posttitle = get_post_field('post_title', $postID); $postcontent = get_post_field('post_content', $postID); $galleries = get_post_meta($postID, '_hb_gallery', true); $returndata = '<div class="hb_single_room room-popup" id="popup-room-' . $postID . '"> <div class="summary entry-summary"> <div class="title"> <h4> <a href="#">' . esc_html($posttitle) . '</a> <img class="close-room-popup" room_id="' . $postID . '" alt="x" src="https://www.micasas.it/wp-content/uploads/2018/03/x.png"> </h4> </div>'; // 记得补充完整你的HTML结构 $returndata .= '</div></div>'; return $returndata; }
注意:我添加了esc_html()来转义标题,避免XSS风险,这是WordPress开发的最佳实践。
2. 修正前端AJAX的dataType设置
因为API返回的是HTML,所以把dataType改为html,或者直接去掉这个参数让jQuery自动判断:
var roomID = jQuery(this).closest('li').attr('id'); // 先确认roomID是有效的数字ID console.log('获取到的roomID:', roomID); jQuery.ajax({ url: '/wp-json/api/hotelRooms', data: { 'post_id': roomID }, type: 'POST', dataType: 'html', // 匹配返回的内容类型 success: function (data) { jQuery(".rooms-popups-container").empty().append(data); console.log('返回的内容:', data); }, error: function (xhr, status, error) { console.log('请求错误:', status, error); } });
额外排查建议
- 在AJAX请求前打印
roomID,确认它是有效的文章ID(数字格式),避免传递了非数字值。 - 如果是登录用户访问,检查该用户是否有阅读对应文章的权限,避免权限问题导致内容无法获取。
内容的提问来源于stack exchange,提问作者milen
相关产品推荐
相关产品推荐

