使用java初始化JavaScript变量

时间:2012-09-29 18:18:03

标签: java javascript jquery jsp

我们可以在jsp页面中用java初始化JavaScript变量吗? 等,

<script type="text/javascript">
var refreshId = setInterval(function() {
    var nv=<% out.print(num_voted); %>;
    var tv=<%out.print(totalvoted); %>;
    var m=<% out.print(month);%>;
    var y=<% out.print(year);%>;
    alert("refreshed");
    $('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
 </script>

代码未按预期工作。 :(

有办法做到这一点吗?为什么不可能通过这种方式?我们需要创建标题才能执行此操作吗?

1 个答案:

答案 0 :(得分:1)

以下是在JSP中设置Javascript变量的示例。

<head>
<%
    String numVotedStr = request.getParameter("numvoted");
    int numVoted = 0;
    if (numVotedStr != null) {
        numVoted = Integer.parseInt(numVotedStr);
    }
%>
<script type="text/javascript">
    function setInterval() {
        alert("hello " + <%= numVoted %>);
    }
</script>
</head>

<body>
<form>
    <input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>

要进行测试,请使用此网址的相应版本:

http://localhost:8080/sandbox/example.jsp?numvoted=99

这将在HTTP请求中弹出一个带有“numvoted”的整数值的警告框,方法是生成一个HTML页面,其中的值在Javascript中初始化。 (代码应该至少有parseInt()调用的try-catch,但这只是一个简单的例子。)