将 "enctype" 属性设置为 "application/json"

Set "enctype" attribute to "application/json"

这是我发出 POST 请求的代码:

function post(path, params, method) {
  method = method || "post"; // Set method to post by default if not specified.

  // The rest of this code assumes you are not using a library.
  // It can be made less wordy if you use one.
  var form = document.createElement("form");
  form.setAttribute("method", method);
  form.setAttribute("action", path);
  form.setAttribute("enctype", "application/json");
  for(var key in params) {
    if(params.hasOwnProperty(key)) {
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", key);
      hiddenField.setAttribute("value", params[key]);

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

我试图通过将表单的 enctype 设置为 "application/json" 来将 HTTP header 中的 Content-type 设置为 "application/json"。但是,它不起作用。

我看到一个 unofficial draft 关于支持 "application/json" enctype 但是它似乎还没有被接受..

有没有人知道如何发出 POST 请求并使用 JSON 而不是 formdata 作为数据格式而不求助于 AJAX?

Does anyone have ideas about how to make a POST request and use JSON instead of formdata as the data format without resorting to AJAX?

目前的浏览器无法做到这一点。

如果您正在编写一个需要正常表单提交的 HTTP 端点,请将其编写为接受 application/x-www-form-urlencodedmultipart/form-data 编码数据。