Set “enctype” attribute to “application/json”

放肆的年华 提交于 2019-12-07 09:42:56

问题


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:


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.



来源:https://stackoverflow.com/questions/31934999/set-enctype-attribute-to-application-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!