gpt4 book ai didi

javascript - 如何将数据从Java方法发送到javascript函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:36 24 4
gpt4 key购买 nike

我使用 Java 脚本创建了一个弹出窗口。我想在弹出窗口上显示一个从 Java 方法返回的字符串。我创建了一个 Controller 并映射了参数。但字符串显示不正确。

这是我的java脚本函数,它显示弹出窗口,但字符串值没有显示。

<script>

function myFunction() {

alert(${random_number});
}
</script>

这是我想要生成的字符串的java方法。

public class VerificationCode {

final static int numOfDigits = 4;
String PINString = "";
int randomPIN = 0;

public String RandomNumber() {

for(int i = 0; i<numOfDigits; i++){
randomPIN = (int)(Math.random() * 8) + 1;
PINString = PINString+String.valueOf(randomPIN);
}

return PINString;
}

}

这是我写的 Controller 。我想知道这是否正确,因为我对此经验较少。

public class PopupController {

@RequestMapping(value = "/register-login", method = RequestMethod.POST)
public String viewUserRegistrationPage(ModelMap model) {
VerificationCode vc = new VerificationCode();
String print_val = vc.RandomNumber();
model.addAttribute("random_number", print_val);
//return "text";
return "user-management";
}

}

我想要做的是在使用java脚本函数“myFunction()”创建的弹出窗口上显示字符串值“PINString”。我使用 IntelliJ 作为我的 IDE 和 JBoss 服务器。

编辑:相关 HTML 表单

<div class="form-group">
<div class="col-sm-8 col-sm-offset-4 col-md-offset-4" onclick="myFunction()">
<input type="submit" value="Register"
class="btn btn-primary btn-flat w-min-120"
data-toggle="modal" data-target="#myModal"/>
</div>
<input type="hidden" id="myInput" value="${random_number}">
<script>

//When the user clicks on div, open the popup
function myFunction() {
//var str = VerificationCode.RandomNumber();
alert("myInput");
}
</script>
</div>

最佳答案

我猜你需要更新你的 JS 函数:

<script type="text/javascript">  
function myFunction(){
var number=document.getElementById("myInput").getAttribute("value");
alert(number);
}
</script>

在html页面中应包含jSTL标签并添加表达式:

<c:out value='${random_number}'/>

HTML 代码:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<div class="form-group">
<div class="col-sm-8 col-sm-offset-4 col-md-offset-4" onclick="myFunction()">
<input type="submit" value="Register"
class="btn btn-primary btn-flat w-min-120"
data-toggle="modal" data-target="#myModal"/>
</div>
<input type="hidden" id="myInput" value="<c:out value='${random_number}'/>">
<script>

//When the user clicks on div, open the popup
function myFunction() {
//var str = VerificationCode.RandomNumber();
alert("myInput");
}
</script>
</div>

关于javascript - 如何将数据从Java方法发送到javascript函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com