Struts 2 jquery autocompleter with JSON
I'm using atocompleter in 开发者_如何学编程my form with json.
This is the part of my struts.xml
<package name="json" namespace="/" extends="json-default">
<result-types>
<result-type name="json" class="com.googlecode.jsonplugin.JSONResult" />
</result-types>
<action name="test" class="testClass" method="populate">
<result type="json" name="success">
<param name="root">itemList</param>
<param name="contentType">text/html</param>
</result>
</action>
</package>
This is the jsp
<s:form id="frm_demo" name="frm_demo" theme="simple" action="test2">
<s:url id="remoteurl" action="test" />
<sj:autocompleter
id="lst"
name="lst"
list="%{remoteurl}"
listValue="name"
listKey="id"
selectBox="true"
/>
<s:submit value="submit"/>
</s:form>
This is the action class method
public String populate() throws Exception{
itemList.put("1", "a");
itemList.put("2", "b");
itemList.put("3", "c");
return "success";
}
With the above code in struts.xml my jsp renders like this.{"3":"c","2":"b","1":"a"}
But when I delete the "contentType" parameter, in other words the content type is "application/json" the jsp pops the download window. I need theauto completer to return the key when i click submit button. But the page doesn't load with the autocompleter. Any solutions? p.s. itemList i used in my action class is a HashMap... does that matter?
Using map is OK with collection-backed components. I think there's couple of problems with your code.
First in you action configuration you have set the root object to your itemList
, this way only content of the list will be converted to json so you can't refer to the list itself in your autocompleter.
Second you have to set the href
attribute for your autocompleter and set the remoteUrl
as it's value. So your code could be like:
<package name="json" namespace="/" extends="json-default">
<action name="test" class="testClass" method="populate">
<result type="json"/>
</action>
</package>
In your autompleter:
<s:form id="frm_demo" theme="simple" action="test2">
<s:url id="remoteurl" action="test" />
<sj:autocompleter href="%{remoteurl}"
id="lst"
name="lst"
list="itemList"
listValue="name"
listKey="id"
selectBox="true"/>
<s:submit value="submit"/>
</s:form>
See if that works.
I think your code is ok,Just remove this code
<param name="contentType">text/html</param>
精彩评论