在Java函数中使用javascript变量 [英] using javascript variable inside the java function
问题描述
需要一个有关如何在java作用域内访问javascript变量的解决方案. 在以下代码中,<%= toppings [k]%> k是一个JavaScript变量,我如何访问它,我收到一条消息,因为 JVM不知道k
wanted a solution on how to access the javascript variable inside the java scope. In the below code, <%=toppings[k]%> k is a javascript variable how can i access that, I am getting a message as k is not known to JVM
function value_transitAccountCounter(i){
alert('welcome -->'+i);
for(var k=0;k<5;k++){
if(i==k){
return '<%=toppings[k]%>';
}
}
}
推荐答案
您的Java代码在服务器上运行 .您的JavaScript代码正在客户端上运行 .因此,您不能在服务器上使用k
,在页面完成,发送到浏览器并执行其中的JavaScript之前,它不存在.
Your Java code is running on the server. Your JavaScript code is running on the client. So you can't use k
on the server, it doesn't exist until the page is finished, sent to the browser, and the JavaScript therein executed.
从您的代码看来,您只需要访问存储在服务器端toppings
数组中的字符串.您有两种选择:
From your code, it looks like you just need to access the strings stored in the server-side toppings
array. You have two choices:
-
将整个
toppings
数组作为JavaScript数组输出到页面的脚本.然后,您可以在客户端使用它.
Output the entire
toppings
array to the page's script as a JavaScript array. Then you can just use it client-side.
让您的value_transitAccountCounter
函数进行 ajax调用您的服务器端代码,询问toppings[i]
的值是什么.您需要更改value_transitAccountCounter
以接受用于返回值而不是实际返回值的回调,因为ajax调用将是异步的(value_transitAccountCounter
将在ajax调用完成之前返回,因此,在获得值). (进行同步ajax调用是可能,但这是一个非常非常糟糕的主意,您最好假装这是不可能的.它完全锁定了大多数浏览器的UI,而调用时执行,令人难以置信使用户烦恼.)
Have your value_transitAccountCounter
function make an ajax call to your server-side code, asking what the value of toppings[i]
is. You'll need to change value_transitAccountCounter
to accept a callback to use to return the value rather than actually returning it, because the ajax call will be asynchronous (value_transitAccountCounter
will return before the ajax call completes and thus, before you have the value to return). (It's possible to make synchronous ajax calls, but it's a very, very bad idea and you're better off pretending it isn't possible. It completely locks up the UI of most browsers while the call is executing, incredibly irritating for users.)
这篇关于在Java函数中使用javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!