需要将值从 JavaScript 传递到 servlet 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6897881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:16:00  来源:igfitidea点击:

Need to pass a value from JavaScript to a servlet page

javascripthtmlservlets

提问by Coder_sLaY

How do I pass a value from JavaScript code to a servlet page?

如何将值从 JavaScript 代码传递到 servlet 页面?

回答by Sandeep Pathak

As per my understanding , Create a hidden input field , set the value and submit to the action and get the hidden field value from servlet.

根据我的理解,创建一个隐藏的输入字段,设置值并提交到操作并从 servlet 获取隐藏字段值。

This shows a kick-off example , you can modify it according to your needs : HTML Form :

这显示了一个启动示例,您可以根据需要对其进行修改: HTML 表单:

<form name="myForm">  
<input type=hidden name="hiddenValue"/>  
<input type="submit" value="Submit" name="buttonSubmit" onclick="customSubmit(10)"/>  
</form>  

Script :

脚本 :

<script>  
 function customSubmit(someValue){  
 document.form1.hiddenValue.value = someValue;   
 document.form1.submit();  
 }  
</script>  

You would user Request.getParameterto get this value from servlet .

您将使用Request.getParameter从 servlet 获取此值。

回答by Karan Shah

With a field as follows:

带有如下字段:

<INPUT TYPE="HIDDEN" NAME="variableName" VaLUE="">

Then in Javascript you can do:

然后在 Javascript 中,您可以执行以下操作:

document.form.variableName.value="value";
form.submit();

and the JSP can evaluate the param "variableName". Remember though, that a Parameter is always a String (or an array of strings if accessed through a different method) so you will need a way to transform this string to what you want, if you want something other than a String (e.g. an Integer).

并且 JSP 可以评估参数“variableName”。但请记住,参数始终是字符串(如果通过不同的方法访问,则为字符串数组),因此,如果您想要字符串以外的其他内容(例如,整数),您将需要一种方法将此字符串转换为您想要的)。

Bt to tell you the truth I am not sure what you by a null value in javascript. Don't forget that anything that the JSP reads from the params, must then turn around and insert the value back into the hidden field to be read by the javascript on the client (or actually modify the javascript in the JSP before returning the html to the client).

Bt 说实话,我不确定你在javascript 中的空值是什么。不要忘记 JSP 从 params 中读取的任何内容,然后必须翻转并将值插入回隐藏字段中以供客户端上的 javascript 读取(或者在将 html 返回到之前实际修改 JSP 中的 javascript客户端)。