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
252 views
in Technique[技术] by (71.8m points)

struts2: update second select based on first select value using javascript and jquery

I am working on a struts2 project where I have 3 html select controls each one being dependent on the previous selection. Say the first select is for country, second for state, third for city. The list of options in the state select would be filtered to only display the states in that country and so on. Due to some other limitations I am using the basic html select control instead of struts2's. Here is a sample of how I am currently populating the select:

<select id="stateSelect"  name="selectedState">
<s:iterator value="#session['myModel'].states" status="itr">
     <option value="<s:property value="code"/>">
      <s:property value="label"/>
</option>
</s:iterator>
</select>

I think that what I need to do is onchange event do an ajax call to retrieve the list of "states" based on the selected "country". The questions are:
1. how can I do this ajax call using jquery?
2. what do I need to pass as the url for the ajax call? just the action name?
3. how can I parse the results back? From java code I can return a list of "State" objects that have "code" and "label" and other properties. How can I parse this list in javascript and generate the proper options for the select tag?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Generally, the way to do this is using the Struts2 JSON plugin which ships with recent versions of Struts2. To interact with jQuery in your JSP you'll want to use s:url to create a URL for your JSON action and then you can invoke it using jQuery's .getJSON() or .load().

However, if your dropdown choices really aren't that complicated, don't over-architect. It can be easier to render them all using s:iterator on the initial page load and use .change() on your dropdown boxes to either move the data between select components, or augment the name attribute on one of the select boxes for the form submit.


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

...