Set “enctype” attribute to “application/json”

2019-05-12 15:15发布

Here is my code for making POST request:

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();
}

I tried to set the Content-type in HTTP header to "application/json" by setting enctype of the form to "application/json". However, it doesn't work.

I saw an unofficial draft about supporting "application/json" for enctype however it seems not accepted yet..

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?

1条回答
放荡不羁爱自由
2楼-- · 2019-05-12 15:37

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?

There is no way to do this in current browsers.

If you are writing an HTTP endpoint that expects normal form submissions, write it so it accepts application/x-www-form-urlencoded and multipart/form-data encoded data.

查看更多
登录 后发表回答