天天看點

jquery AutoComplete 插件與struts2內建

AutoCompleteAction.java

@SuppressWarnings("serial")

@ParentPackage(value = "actions" )

public class AutoCompleteAction extends ActionSupport{

public static final Log LOG = LogFactory.getLog(AutoCompleteAction.class);

//注入keywordsService

private KeywordsService keywordsService;

//傳回的關鍵詞清單

private List<String> words;

private String q;

/** 處理自動完成請求 */

@Action(value = "/autoComplete", results = { @Result(name = "success", type="json") })

public String autoComplete(){

words = new ArrayList<String>();

List<String> keywords = keywordsService.queryWords(q);

System.out.println(keywords.size());

for(int i = 0; i < keywords.size(); i++){

if(i < 10){//取10個詞

words.add(keywords.get(i));

}

}

return SUCCESS;

}

@JSON(serialize=true)

public List<String> getWords() {

return words;

}

public void setWords(List<String> words) {

this.words = words;

}

public KeywordsService getKeywordsService() {

return keywordsService;

}

public void setKeywordsService(KeywordsService keywordsService) {

this.keywordsService = keywordsService;

}

public String getQ() {

return q;

}

public void setQ(String q) {

this.q = q;

}

}

需引入js檔案

<mce:script type="text/javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>

<mce:scripttype="text/javascript" src="./js/ui/jquery.ui.core.js"></mce:script>

<mce:script type="text/javascript"src="./js/ui/jquery.ui.widget.js"></mce:script>

<mce:script type="text/javascript"src="./js/ui/jquery.ui.position.js"></mce:script>

<mce:script type="text/javascript"src="./js/ui/jquery.ui.autocomplete.js"></mce:script>

前台請求js

$(document).ready(function(){

$( "#q" ).autocomplete({

minLength: 1,

source: function( request, response) {

$.ajax({

url: "autoComplete.action",

dataType: "json",

data: {

q: $("#q").val()

},

success:function(json){

response( $.map( json.words, function( name ) {

return {

label: name,

value: name

}

}));

}

});

}

});

其中q為你想要添加自動完成的文本框如:

<input type="text" name="q" id="q" >