本文介绍了设置"enctype"属性为"application/json"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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..

有人对如何发出POST请求并使用JSON而不是formdata作为数据格式有任何想法吗?

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.

如果您编写的HTTP端点需要正常的表单提交,请编写该端点,以便它接受application/x-www-form-urlencodedmultipart/form-data编码的数据.

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.

这篇关于设置"enctype"属性为"application/json"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 20:01