javascript - 使用 POST 将数据从 .js 发送到 JSON
问题描述
我有一些用户正在填写的输入,为了简化事情,它只是名字/姓氏。我的想法是让这些数据能够编辑我在本地拥有的 JSON 文件来添加这些信息。我不知道这是否可能。这是我的 .js 代码:
function submitContacto(e) {
var name= $("#name").val();
var surname= $("#surname").val();
var toSend={
[name] : name,
[surname] : surname,
};
var jsonString = JSON.stringify(toSend);
console.log(jsonString);
const xhr = new XMLHttpRequest();
xhr.open("POST", "./contactJSON");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(jsonString);
}
截至目前,控制台记录了正确创建的 jsonString,但是我出现了一个错误,显示“POST http://127.0.0.1:5500/contactJSON 405 (Method Not Allowed)”。我不确定这个错误是因为我做错了什么,还是无法直接从 JavaScript 文件发送数据来编辑 JSON 文件。
解决方案
现在允许的方法意味着 url 是好的,但方法不是。
所以这里POST
不允许。你可以验证curl '' -X POST
如果您的服务器编码正确,请在终端中发送此请求:
curl 'http://127.0.0.1:5500/contactJSON' -i
并检查 的值Allow
。
HTTP/1.1 200 OK
Date: Sat, 28 Nov 2020 11:18:28 GMT
Content-Type: application/json
Content-Length: 2
Connection: keep-alive
Allow: GET
顺便说一句,当前浏览器实现了 fetch API,看看
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
推荐阅读
- javascript - 如何根据信息表绘制动态折线图?
- c# - 删除 EWS EmailMessage 正文中的 HTML 部分
- javascript - 替换所有以冒号开头的字符串,例如快速路由路径
- c++ - 如何在 Windows 上检查 EXE 是否具有 /GS 安全保护?
- java - 在 SonarQube 中使用枚举错误计算开关条件
- git - 设置后无法推送 git 提交
- html - 不太擅长 css 需要修复以匹配我的旧代码
- java - 如何处理 List IndexOutOfBoundsException?
- objective-c - 在目标 c 中编码 URL 参数
- ios - 在 Xcode 11 中为旧源代码启用自动布局