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

点击按钮第二次时PHP文件路径异常引发404错误的技术问询

问题解决:JS调用PHP路径二次请求404错误

问题原因

问题核心在于相对路径的解析逻辑变化:首次请求时,components/data.php作为相对路径,会基于当前页面的URL(比如http://xxx.com/page.html)解析为http://xxx.com/components/data.php;但二次点击时,页面的基准路径可能因路由变化、AJAX内容加载后的状态改变,导致相对路径被解析为根目录绝对路径/components/data.php,若服务器上该路径不存在,就触发404。

解决方案

方案1:使用明确的绝对路径

直接指定基于网站根目录的绝对路径(需匹配服务器上文件的实际位置),或者使用完整域名路径:

// 基于网站根目录的绝对路径,根据项目实际结构调整
const baseUrl = "/components/data.php";

// 或者使用完整域名路径(更可靠,不受页面路径影响)
// const baseUrl = window.location.origin + "/components/data.php";

方案2:动态生成正确的基准路径

利用document.baseURI或window.location动态拼接路径,确保始终基于当前页面的基准URL解析:

// 基于当前页面的基准URI生成正确路径
const baseUrl = new URL("components/data.php", document.baseURI).href;

function loadData(requestType, containerSelector, limitVal, offsetVal) {
  const container = document.querySelector(containerSelector);
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      container.innerHTML = xhr.responseText;
    }
  };
  // 直接使用已生成的绝对路径拼接参数
  xhr.open("POST", `${baseUrl}?requestType=${requestType}&limit=${limitVal}&offset=${offsetVal}`, true);
  xhr.send();
}

方案3:检查页面base标签

如果页面中存在<base>标签,确认其href属性是否被动态修改,确保其指向正确的基准路径,避免干扰相对路径解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:12:45