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

表单提交触发405 (Method Not Allowed)错误,PHP接口请求失败

问题描述

开发可提交用户邮件内容的表单时,点击提交按钮控制台出现405 (Method Not Allowed)错误。当前使用VS Code的Live Server工具,希望能测试显示PHP文件返回的文本,相关代码如下:

HTML代码

<form>
  <div class="fields">
    <div class="field">
      <input
        type="text"
        placeholder="Enter your first name"
        name="first-name"
      />
      <i class="fa-solid fa-user"></i>
    </div>

    <div class="field">
      <input type="text" placeholder="Enter your last name" name="last-name" />
      <i class="fa-solid fa-user"></i>
    </div>

    <div class="field">
      <input type="text" placeholder="Enter your Email" name="email" />
      <i class="fa-solid fa-envelope"></i>
    </div>

    <div class="field">
      <input type="text" placeholder="Subject" name="subject" />
      <i class="fa-solid fa-pen"></i>
    </div>
  </div>

  <div class="message">
    <textarea placeholder="write a message" name="message"></textarea>
    <i class="fa-solid fa-message"></i>
  </div>

  <div class="send-button">
    <button type="submit">Send message</button>
    <span>sending your message ...</span>
  </div>
</form>;

JS代码

const form = document.querySelector("#contact form");
const statusText = document.querySelector(".send-button span");

form.addEventListener("submit", (e) => {
  console.log("clicked");
  e.preventDefault();
  statusText.style.display = "block";

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "message.php");
  xhr.onload = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let response = xhr.response;
      console.log(response);
    } else {
      console.log("error has been occured");
    }
    console.log(xhr.response);
  };
xhr.send();
});

PHP代码(message.php)

<?php 
  echo "this text is from PHP";
?>
问题原因及解决方案

原因

Live Server是静态文件服务器,仅能处理HTML/CSS/JS等静态资源,不支持解析PHP代码;同时静态服务器默认只接受GET请求,对POST请求会直接返回405 Method Not Allowed错误。

解决方案

  1. 换用支持PHP的本地服务器

    • 用PHP内置服务器:在项目根目录打开终端,执行命令 php -S localhost:8000,随后在浏览器访问http://localhost:8000即可测试。
    • 或者安装XAMPP、WAMP等集成环境,将项目放入服务器根目录(如XAMPP的htdocs文件夹),启动服务器后访问对应地址。
  2. 补充表单数据提交(可选)
    当前JS中xhr.send()未传递任何表单数据,若需要提交用户输入内容,可修改JS代码添加数据收集逻辑:

    // 在xhr.open之后添加
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // 收集表单数据
    const formData = new FormData(form);
    const params = new URLSearchParams(formData).toString();
    // 发送数据
    xhr.send(params);
    

    修改后PHP端可通过$_POST获取表单字段的值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:47:31