我的主页上有一个表单和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>
如果它在JavaScript Promise函数之外, document.getElementById('hiddeninput').value = "whatever"
可以正常工作(它已成功地与表单的其余部分一起发布)。
然而,当它在JavaScript Promise函数内部时它不起作用。根据我的理解,你不能将值从JavaScript Promise返回到更高的范围,所以我是否有可能从Promise函数访问result
,这样我就可以将它设置为{{1 }}?
答案 0 :(得分: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>