javascript - 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,但它也会引发同样的错误。现在我该怎么做?我怎样才能让它工作?
解决方案
错误不在来自服务器的 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
),尝试删除正文的部分以查看它是否适用于子集。
推荐阅读
- javascript - 如何做到这一点,以便当我单击图像元素时,它会添加一个显示 .title、.artist、.album 和 .year 的警报?
- ant - 如果元素尚不存在,有没有办法将元素附加到 xml
- c - 在 C 编程中比较两个文件以匹配行
- php - 为 PHP Web 应用程序捆绑 JS 和 CSS?
- c - 我在使用函数将字母分配给结构的 char 变量时遇到问题
- vb.net - Visual Basic 的类型推断如何与 Equals 运算符一起使用
- javascript - 如何使用javascript从html表单中读取数组数据
- kotlin - 如何使用 spring rest docs 可视化我的 index.html 页面
- c++ - 在查找子集时元素和元素数量之间的二进制比较背后的逻辑是什么?
- abp - 在身份管理网格和编辑视图中显示自定义属性