Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how can i pass value from javascript to a java class in struts2?

function redirect(id){
alert(id);

document.forms["AddToCart"].submit();
}

This is my javascript. How can i pass the value of 'id' into AddToCart.java. I am using struts2 framework.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are many ways to do this and one of the easy way is to pass it as a hidden form field

something like

<s:hidden value="" name="my_ID" id="my_ID"/>

and in you javascript you need to set this hidden input field like

function redirect(id){
alert(id);
document.getElementById("my_ID").value=id;
document.forms["AddToCart"].submit();
}

final step is to create a similar property in your action class with its getter and setters and framework will inject the form value in the respected property

public class MyAction extends ActionSupport{

  private String my_ID  // data type can be as per your requirements
  getter and setters

  public String execute() throws Exception{
     return SUCCESS;
  }

}

this is all you need to do and you will able to get the value inside your action class under my_ID property. I am assuming that AddToCart is your Struts2 Action class else you need to pass the value to your class from your called action.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...