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

WordPress插件调用酒店API时URL显示undefined致404错误求助

WordPress插件调用酒店API时请求URL出现undefined导致404错误的排查方案

核心问题分析

请求URL显示undefined/content-api/1.0/countries,说明前端JavaScript获取的endpointUrl值为undefined,导致拼接后的URL无效,触发404错误。以下是具体排查和解决步骤:


1. 修复前端输入框的ID缺失问题

你的HTML表单中,Endpoint URL的输入框仅设置了name属性,未添加id属性,导致JS通过$('#endpoint_url')无法找到该元素,val()返回undefined。

修改HTML代码:
在input标签中添加id="endpoint_url",同时闭合未正确结束的</td>标签:

<tr valign="top">
    <th scope="row">Endpoint URL:</th>
    <td><input type="text" name="endpoint_url" id="endpoint_url" value="<?php echo $endpoint_url; ?>" /></td>
</tr>

2. 增加前端输入验证(可选但推荐)

在发起AJAX请求前,先检查输入值是否为空,避免无效请求:

$('#get-all-countries-button').click(function() {
    var endpointUrl = $('#endpoint_url').val().trim();
    var apiKey = $('#api_key').val().trim();
    var secretKey = $('#secret_key').val().trim();

    // 输入验证
    if (!endpointUrl) {
        $('#all-countries-result').html('<p>请先填写Endpoint URL</p>');
        return;
    }
    if (!apiKey || !secretKey) {
        $('#all-countries-result').html('<p>请完整填写API凭证</p>');
        return;
    }

    // 后续AJAX代码...
});

3. 确认WordPress选项已正确保存

检查你的插件设置保存逻辑,确保endpoint_url已被正确存储到WordPress选项中。如果缺少保存代码,添加以下PHP逻辑(通常在设置页面的提交处理部分):

// 处理设置表单提交
if (isset($_POST['submit']) && check_admin_referer('your_plugin_settings_nonce')) {
    if (isset($_POST['endpoint_url'])) {
        update_option('endpoint_url', sanitize_text_field($_POST['endpoint_url']));
    }
    if (isset($_POST['api_key'])) {
        update_option('api_key', sanitize_text_field($_POST['api_key']));
    }
    if (isset($_POST['secret_key'])) {
        update_option('secret_key', sanitize_text_field($_POST['secret_key']));
    }
    // 添加成功提示
    add_settings_error('your_plugin_settings', 'settings_saved', '设置已保存', 'updated');
}

4. 额外安全提示(非当前404问题,但需注意)

当前代码中,Signature是通过PHP渲染的固定值,基于服务器端获取的secret_key计算。但如果用户在前端修改了secretKey,这个签名不会同步更新,且secret_key暴露在前端存在安全风险。建议:

  • 不在前端传递secret_key,改为通过后端代理请求API(前端调用WordPress自定义REST接口,由后端处理API请求并签名)
  • 若必须前端计算签名,需在JS中对输入的secretKey重新计算MD5:
    var signature = md5(secretKey); // 需要引入MD5库,如crypto-js
    

内容的提问来源于stack exchange,提问作者grimfate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 14:25:20