【问题标题】:Adding JavaScript Promise result to hidden input field将 JavaScript Promise 结果添加到隐藏的输入字段
【发布时间】:2017-03-11 05:04:35
【问题描述】:

我的主页上有一个表单和 JS 承诺功能:

<form action="/run.php" method="POST" target="_blank" id="myform">
    <input type="hidden" name="hiddeninput" id="hiddeninput">
    <input type="text" name="userinput" id="userinput">
    <button type="submit">Go!</button>
</form>

<script>
document.getElementById('myform').onsubmit = function go() {

    // get user input + other unrelated info
    .then(function(adding) {
            // calculations
            result = x;
        });

    document.getElementById('hiddeninput').value = "whatever"
}
</script>

document.getElementById('hiddeninput').value = "whatever" 在 JavaScript Promise 函数之外有效(它与表单的其余部分一起成功发布)。

但是,当它在 JavaScript Promise 函数中时它不起作用,据我了解,您无法将 JavaScript Promise 中的值返回到更高的范围,所以有什么方法可以访问 result来自 Promise 函数,以便我可以将其设置为等于 document.getElementById('hiddeninput').value?

【问题讨论】:

  • 只需将设置器移动到then 内的value
  • 我已经尝试过了,如上所述,由于某种原因它不起作用(虽然控制台日志记录有效,但不能发布)
  • 您的表单正在提交,您必须先阻止它。
  • 知道我该怎么做,所以它只在 Promise 函数解决后提交?
  • 您必须分两步完成。

标签: javascript jquery html forms promise


【解决方案1】:
<form action="/run.php" method="POST" target="_blank" id="myform">
    <input type="hidden" name="hiddeninput" id="hiddeninput">
    <input type="text" name="userinput" id="userinput">
    <button type="submit">Go!</button>
</form>

<script>
document.getElementById('myform').onsubmit = function go(event) {
     var form = this;
     event.preventDefault();
    // get user input + other unrelated info
    .then(function(adding) {
            // calculations
            result = x;
            document.getElementById('hiddeninput').value = result;
           form.submit();
        });


}
</script>

【讨论】:

  • onsubmit 将在 promise 解决之前完成
  • 没有办法防止吗?
  • no promise 是异步的,所以 onsubmit 会在 promise resloving 之前完成它的执行,但是 onsubmit 在有人提交表单之前不会开始。有什么问题吗?我不明白你为什么要阻止它。
  • 因为 Promise 使用 userinput 值来计算结果。所以document.getElementById('hiddeninput').value = result需要在POST之前解决,否则我无法使用hiddeninput的值。
猜你喜欢
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多