繁体   English   中英

如何将数据从Java方法发送到Java脚本函数?

[英]How to send data from Java method to java script function?

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

这是我的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;
}

}

这是我写的控制器。 我不知道这是否正确,因为我对此经验不足。

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM