首页 > 解决方案 > 使用 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 文件。

标签: javascriptjsonajaxxmlhttprequest

解决方案


现在允许的方法意味着 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


推荐阅读