【发布时间】: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