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

WooCommerce结账页切换省份后配送方式不更新,JSON解析失败

问题解决指南

1. 修复JSON响应末尾的0(核心问题)

PHP代码中,AJAX回调函数执行完echo json_encode($data);后,WordPress会自动输出一个0,导致JSON格式错误。解决方法是在echo后立即终止脚本:

修改yalidine_woocommerce.php中的回调函数:

function yalidine_shippings_methods() {
    $data = [];
    if(isset($_POST['action']) && $_POST['action'] == 'yalidine_shippings_methods') {
        $wilaya_id = explode('-', $_POST['state']);
        $wilaya_id = (int)$wilaya_id[1];

        $yalidine_options = get_option('WOO_YALIDINE_SETTINGS');
        $api_id = isset($yalidine_options['stopdesk']) ? key($yalidine_options['stopdesk']) : null;
        if($api_id !== null) {
            $api_token = $yalidine_options['stopdesk'][$api_id]['token'];
            $http_request = new CurlHttpRequest();
            $yalidine = new YalidineAPI($http_request);
            $yalidine->setApiKeys($api_id, $api_token);
            $response = $yalidine->getWilayaStopDesks($wilaya_id);
            $response2 = $yalidine->getWilayaDeliveryFees($wilaya_id);
            if(isset($response['total_data']) && $response['total_data'] > 0
                && isset($response2['total_data']) && $response2['total_data'] > 0) {
                foreach($response['data'] as $stopdesk) {
                    $data['stop_desks'][] = $stopdesk['name'];
                }

                $data['fee'] = ['home' => $response2['data'][0]['home_fee'], 'stop_desk' => $response2['data'][0]['desk_fee']];
            }
        }
    }

    echo json_encode($data);
    wp_die(); // 新增:终止脚本,避免WordPress输出0
}

// 修复重复钩子,添加未登录用户权限
add_action('wp_ajax_yalidine_shippings_methods', 'yalidine_shippings_methods' );
add_action('wp_ajax_nopriv_yalidine_shippings_methods', 'yalidine_shippings_methods' );

2. 修复JS中的DOM更新与遍历错误

问题点:

  • 遍历res.stop_desks时用for...in拿到的是数组索引,不是自提点名称
  • shipping_fees变量未明确定义,可能导致DOM操作失败
  • 多余的event.preventDefault()可能干扰下拉框默认行为
  • catch块无错误日志,无法排查解析失败原因

修改main.js:

// 先确保获取到目标元素,替换成实际页面中的元素选择器
let shipping_fees = jQuery('#shipping-fees-row');
let shipping_method;

jQuery('#billing_state').on('change', function() {
    let dataVariable = {
        'action': 'yalidine_shippings_methods',
        'state': this.value 
    };
    jQuery.ajax({
        url: yalidine_shippings_methods.ajaxurl,
        type:'POST',
        data: dataVariable,
        success:function(response) {
            console.log('response:', response);
            let options = ` <option value="pickup">Self pickup</option>
                            <option value="home">Home</option>`;
            try {
                let res = JSON.parse(response);
                // 遍历数组用for...of,拿到实际的自提点名称
                if(res.stop_desks && res.stop_desks.length > 0) {
                    for(const stopdeskName of res.stop_desks) {
                        options += `<option value="${stopdeskName}">${stopdeskName}</option>`;
                    }
                }
                // 更新DOM
                shipping_fees.html('<th>Shipping</th><td data-title="Shipping"><select id="shipping-method-list">' + options + '</select></td>');
                shipping_method = jQuery('#shipping-method-list');
            }
            catch(err) {
                console.error('JSON解析失败:', err); // 新增错误日志,方便调试
            }
        },
        error: function(err) {
            console.error('AJAX请求失败:', err)
        }
    });
});

3. 验证与调试

  • 打开浏览器控制台,查看AJAX响应是否已无末尾的0,JSON格式是否正确
  • 确认shipping_fees的选择器正确指向页面中要更新的元素
  • 测试下拉框切换时,是否能正确加载自提点选项

内容的提问来源于stack exchange,提问作者H Aßdöµ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:18:14