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

本地正常的XML请求部署网站后报错:405及JSON解析异常

问题分析与解决:GitHub Pages部署PHP接口异常

问题现象

本地环境中XML请求可正常运行,但将HTML部署到GitHub Pages(https://amrit.github.io)后出现两类异常:

  • 执行ajaxpost函数发起POST请求至https://amrit.github.io/scripts/sendData.php时,返回net::ERR_FAILED 405错误
  • 执行get_component_states函数发起GET请求至scripts/receiveData.php时,服务器直接返回PHP代码文本,导致JSON.parse触发Uncaught SyntaxError: Unexpected token '<'语法错误

核心原因

GitHub Pages是静态站点托管服务,仅支持HTML、CSS、JavaScript等静态文件的托管,无法解析和运行PHP脚本,这是两个异常的根源:

  • 405错误:服务器不处理针对PHP文件的POST请求,直接返回"方法不允许"的错误响应
  • 返回PHP代码:服务器将PHP文件当作普通静态文本返回,未执行脚本生成预期的JSON数据,前端拿到源码后自然无法完成JSON解析

解决方案

  1. 迁移后端服务:将sendData.php和receiveData.php部署到支持PHP运行的服务器(如虚拟主机、云服务器、Heroku、Vercel等)
  2. 更新前端请求地址:
    • 修改ajaxpost函数中xhr.open的目标URL为新后端的sendData.php地址
    • 修改get_component_states函数中xmlhttp.open的目标URL为新后端的receiveData.php地址

相关代码

ajaxpost函数

function ajaxpost() {
    // (A) GET FORM DATA
    var form = document.getElementById("myForm");
    var data = new FormData(form);

    // (B) AJAX
    var xhr = new XMLHttpRequest();    
    xhr.open("POST", "https://amrit.github.io/scripts/sendData.php");
    //       

    //xhr.open("POST", "scripts/sendData.php");
    // What to do when server responds
    xhr.onload = function() {
        console.log(this.response);
    };
    xhr.send(data);

}

get_component_states函数

function get_component_states() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "scripts/receiveData.php", true);
    xmlhttp.send();           
    xmlhttp.onreadystatechange = function() {
        
        if (this.readyState == 4 && this.status == 200) {
            // update the form with the new values
            // stringify the response
            var response = JSON.parse(this.response);
            //var response = JSON.parse(this.response);
            console.log(response);
            // update the form with the new values
            
            document.getElementsByName("mainVoltage")[0].innerHTML = response.mainVoltage;
            document.getElementsByName("loadPower")[0].innerHTML = response.loadPower;
            document.getElementsByName("exportPower")[0].innerHTML = response.exportPower;
            document.getElementsByName("solarPower")[0].innerHTML = response.solarPower;
            document.getElementsByName("todayKwh")[0].innerHTML = response.todayKwh;
            document.getElementsByName("totalKwh")[0].innerHTML = response.totalKwh;
            document.getElementsByName("circuit1")[0].checked = response.circuit1;
            
        }
        // show the response in the console
        console.log(this.response);
        
    };
    
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:00:55