【问题标题】:Set "enctype" attribute to "application/json"将“enctype”属性设置为“application/json”
【发布时间】:2015-08-11 06:50:11
【问题描述】:

这是我发出 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 标头中的Content-type 设置为“application/json”。但是,它不起作用。

我看到一个 unofficial draft 关于支持 enctype 的“应用程序/json”,但它似乎还没有被接受..

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

【问题讨论】:

  • 看起来来自 DOM 的用于 HTTP 标头的实际值是 HTMLFormElement.encoding 对象属性,即使直接更改,它也会恢复为三个允许值之一,根据 HTML 5 规格:w3.org/TR/html5/forms.html#dom-fs-encoding
  • 所以这不是“可以做到”的问题,而是“即使你尝试,浏览器会忽略你的尝试”,它似乎确实如此。

标签: jquery http forms http-post


【解决方案1】:

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

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

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

【讨论】:

  • Quentin,我想知道,如果我们不能通过 enctype 更改数据类型,他们为什么需要它?我很困惑。我遇到了同样的问题,我也没有解决。有没有办法将数据作为 application/json 发布?
  • 您可以使用enctype 更改数据的编码。您只是不能将其更改为浏览器不知道的编码。
猜你喜欢
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 2012-02-28
  • 2023-03-17
相关资源
最近更新 更多