【发布时间】:2016-08-09 20:57:02
【问题描述】:
长期以来,我一直在使用 vanilla 一段 Javascript,例如:
<form onsubmit="return jsonpost(this);" method=POST action=/validate/>
<label>Firstname: <input required name=firstName></label>
<label>Lastname: <input required name=lastName></label>
<label>Age: <input name=age type=number></label>
<input type=submit>
<form>
<script>
function jsonpost(jsonpostform) {
// collect the jsonpostform data while iterating over the inputs
var data = {};
for (var i = 0; i < jsonpostform.length; i++) {
var input = jsonpostform[i];
if (input.name && input.value) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(jsonpostform.method, jsonpostform.action);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
return false;
}
</script>
序列化表单并通过 XMLHttpRequest 发布。但是我注意到这段代码不能正确处理type=number。有更好的最小模式吗?
【问题讨论】:
-
请添加一些数据来突出您的问题。
-
你能解释一下“不能正确处理数字”是什么意思吗?
-
输入值变成字符串,但数字类型的输入应被视为整数。
-
当你问一个由你的代码引起的问题时,如果你provide code people can use to reproduce the problem,你会得到更好的答案
标签: javascript json forms