You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress中jQuery获取自定义文章类型数据报400错误求助

修复WordPress AJAX获取自定义文章类型数据的400错误问题

核心错误分析

从代码和400错误信息来看,有3个关键问题导致请求失败:

  1. AJAX Action名称不匹配:PHP钩子注册的是webdev_fetch_laptop_post_data,但jQuery里的action参数写的是webdev_fetch_apple_post_data,WordPress找不到对应处理函数,直接返回400。
  2. Post ID获取方式错误:下拉框切换时用$(this).attr('post_id')获取ID,但下拉框本身没有post_id属性,应读取选中选项的value值(前提是渲染下拉框时把post_id存在option的value里)。
  3. get_post函数参数误用:get_post($post_id, $post_type)是错误写法,第二个参数是返回格式(如OBJECT、ARRAY_A),不是post_type,需单独验证文章类型。

完整修复代码

1. 修正后的PHP钩子函数

function webdev_fetch_laptop_post_data() {
    // 验证安全令牌(推荐添加,防止CSRF攻击)
    if (!isset($_GET['nonce']) || !wp_verify_nonce($_GET['nonce'], 'laptop_data_nonce')) {
        wp_send_json_error('无效的安全令牌', 403);
    }

    $post_id = intval($_GET['post_id']);
    $expected_post_type = 'laptop_price_serv';

    // 获取文章对象
    $thispost = get_post($post_id);

    if (!$thispost || $thispost->post_type !== $expected_post_type) {
        wp_send_json_error('未找到ID为' . $post_id . '的有效笔记本文章');
    }

    // 规范返回文章内容
    wp_send_json_success($thispost->post_content);
}

add_action('wp_ajax_webdev_fetch_laptop_post_data', 'webdev_fetch_laptop_post_data');
add_action('wp_ajax_nopriv_webdev_fetch_laptop_post_data', 'webdev_fetch_laptop_post_data');

2. 修正后的jQuery代码

jQuery(document).ready(function($) {
    $("#webdev-laptop-prices-select").on("change", function () {
        var post_id = $(this).val(); // 读取选中选项的value值(对应post_id)
        var nonce = '<?php echo wp_create_nonce("laptop_data_nonce"); ?>';

        $.ajax({
            type: 'GET',
            url: '<?php echo admin_url("admin-ajax.php"); ?>',
            data: {
                'post_id': post_id,
                'action': 'webdev_fetch_laptop_post_data', // 修正为正确的action名称
                'nonce': nonce // 传入安全令牌
            }, 
            success: function (response) {
                if (response.success) {
                    console.log(response.data);
                    // 可将内容渲染到页面,示例:$("#target-container").html(response.data);
                } else {
                    alert(response.data);
                }
            },
            error: function (xhr) {
                console.error('请求错误:', xhr.responseText);
            }
        });
    });
});

额外注意事项

  • 下拉框渲染要求:确保下拉框的option标签格式正确,将post_id存入value属性:
    <select id="webdev-laptop-prices-select">
        <?php
        $laptops = get_posts(array('post_type' => 'laptop_price_serv', 'posts_per_page' => -1));
        foreach ($laptops as $laptop) {
            echo '<option value="' . $laptop->ID . '">' . esc_html($laptop->post_title) . '</option>';
        }
        ?>
    </select>
    
  • 安全规范:添加nonce验证是WordPress开发的最佳实践,能有效防范跨站请求伪造。
  • 响应格式:使用wp_send_json_success和wp_send_json_error会自动设置正确的HTTP状态码与JSON响应头,比直接echo更规范。

内容的提问来源于stack exchange,提问作者M Rafiq Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:45:00