【问题标题】:String value found, but an integer is required找到字符串值,但需要整数
【发布时间】: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


【解决方案1】:

正如 Rayon Dabre 所指出的,type=number 输入仍然是一个字符串。您可以以更智能的方式从表单中收集数据。例如:

// Map of type -> function that converts the value
// Add more converters if you need'em
var type2converter = {number: Number}  

// Converter that does not do anything for fallback
var id = function (x) { return x } 

function getFormData(form) {

    var data = {}
    var converter
    var input

    for (var i = 0; i < form.length; i++) {
        input = form[i]

        if (input.name && input.value) {
            // Get the function that converts the data, or fallback to "dummy-converter"
            converter = converters[input.type] || id
            data[input.name] = converter(input.value)
        }
    }

    return data
}

这样返回的对象将具有您在 HTML 中定义的类型。但它必须在服务器上进行验证。

【讨论】:

  • 感谢伪代码,虽然希望看到一个完整的例子。很想知道其他 JS 框架如何处理这个问题。是不是更容易了?
【解决方案2】:

type=number, 输入元素表示一个控件,用于将元素的值设置为表示数字的字符串

所以type="Number" 的值将是一个字符串,如果转换为有效的浮点数(Number(YOUR_VALUE))

【讨论】:

  • 好的,那么转换应该发生在哪里才能满足s.natalian.org/2016-04-18/schema.json这样的架构??
  • 您申请的是哪个validator?你必须为valid-floating-number测试它...
  • 通用 json 模式验证器
【解决方案3】:

尝试包装调用以检索 parseInt() 中的值 - 例如

parseInt(input.value);

这将检索表单中值的整数表示。不过,您可能需要对其进行一些健全性检查,以确保它是一个 int 并且不会破坏事物。

【讨论】:

  • 我知道如何进行整数转换。 ;) 希望看到一个完整的最小序列化表单来测试数字输入类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 2012-09-20
相关资源
最近更新 更多