首页 > 解决方案 > XMLHttpRequest() POST 返回 405 错误;不允许的方法

问题描述

我的html代码:

    <h2>Please finalize your details</h2>
    <form id="details" method="post" class="form">

        Full name: <strong name="name_1">ABCDEF</strong><br><br>
        ID No:<strong name="org_number_1">123</strong><br><br>
        Mobile No:<strong name="ph_number_1"">1234567890</strong><br><br>
        
        E-mail: <strong name="email_1">ABC@DEF.COM</strong><br><br>
        ID Card: <img src="profile.png" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>

        <button id="go">It's correct</button>
        
    </form>

我的JavaScript:

document.getElementById('go').addEventListener('click', submit);
function submit(){

    var nme=document.getElementsByName("name_1")[0].innerHTML;
    var id=document.getElementsByName("org_number_1")[0].innerHTML;
    var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
    var email=document.getElementsByName("email_1")[0].innerHTML;
    var img=document.getElementsByName("image")[0].src;

    const xhr=new XMLHttpRequest();

    xhr.onload=function(){

        const serverResponse=document.getElementById("response");
        serverResponse.innerHTML=this.responseText;
    };

    xhr.open("POST", "database_registration.php");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("name="+nme+"&id="+id+"&phone="+phone+"&email="+email+"&img="+img); //this line throws the error "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"
}

我在Visual Studio 代码编辑器中执行我的代码,我的项目位置在:

C:\Users\Abhishek\Desktop\Web-dev stuff\XAMPP\htdocs\Stack hack 20 20

这是错误:

在此处输入图像描述

不仅如此,我还尝试过使用Fetch API,但它也会引发同样的错误。现在我该怎么做?我怎样才能让它工作?

标签: javascriptphphtmlxampphttp-status-code-405

解决方案


错误不在来自服务器的 JS 中。里面有什么database_registration.php?如果那没有处理,POST那么我希望服务器返回405.

404将意味着database_registration.php不存在,但405意味着它存在,但不允许POST特别允许。检查allow响应的标头以了解受支持的方法。

尝试:

    xhr.open("GET", "database_registration.php?" + 
        "name="+nme+"&id="+id+"&phone="+phone+"&email="+email+"&img="+img);
    xhr.send();

GET而是提出请求。

或者,这可能是解析发布的内容时出错(误报,应该400或可能406),尝试删除正文的部分以查看它是否适用于子集。


推荐阅读