I am intending to display a list of suggestions for a textbox using sj:autocompleter
. When I hard code the data in the jsp it works fine.
<sj:autocompleter name="fruitNames"
list="{'apple', 'banana', 'orange', 'apricot'}"
label="Fruit Names">
</sj:autocompleter>
But I want to get the list of suggestions dynamically from the action class. I tried doing this but it is not getting the values.
<sj:autocompleter name="fruitNames" list="fruitslist"
label="Fruit Names">
</sj:autocompleter>
In my action class,
public String execute() {
fruitslist= new ArrayList<String>();
fruitslist.add("Apple");
fruitslist.add("Banana");
fruitslist.add("Orange");
fruitslist.add("Apricot");
}
Please help.
Ensure you have a getter:
public List<String> getFruitslist() {
return fruitslist;
}
Since you posted your struts.xml and now it's clear that you want to use JSON, the code must be changed. The previous answer was referring to a standard Array from the main Action; in case of a JSON action, you need to specify an url in href
attribute of the autocompleter to point to the separate JSON Action:
<s:url var="remoteurl" action="ajaxAction"/>
<sj:autocompleter
id="fruitslist"
href="%{remoteurl}"
delay="50"
loadMinimumCount="2"
/>
Then you need to set your result as JSON, and your root
object to your Array, like this:
<action name="ajaxAction" class="org.struts.action.AjaxJsonAction">
<result name="success" type="json">
<param name="root">
fruitslist
</param>
</result>
</action>
I strongly suggest you to read how the Struts2-JSON plugin works.
来源:https://stackoverflow.com/questions/26515993/autocomplete-a-textbox-using-sjautocompleter-with-a-dynamic-list