jQuery-uiのautocompleteで遊んでみる

  • eclipse 4.2
  • MaxOS10.8.2

ajaxでjsonpをあらかじめ取得しておき、autocompleteにわたすサンプル

jspで取得する値はmemcachedに入っている

  • sample.jsp
<%@ page language="java" contentType="text/html; charset=Shift_JIS"
		pageEncoding="Shift_JIS"%>
<%@ page import="java.util.*" %> 
<%@ page import="java.net.*" %>	 
<%@ page import="net.rubyeye.xmemcached.*" %>
<%@ page import="net.rubyeye.xmemcached.utils.*" %>
<%@ page import="net.rubyeye.xmemcached.exception.*" %>
<%--
memcachedに以下のデータが入っている
key,value
1,value1
2,value2
3,value3
..

出力はJsonp
[ {"label":"1","tag":"value1"} , {"label":"2","tag":"value2"} , {"label":"3","tag":"value3"} , {"label":"4","tag":"value4"} , {"label":"5","tag":"value5"} , {"label":"6","tag":"value6"} , {"label":"7","tag":"value7"} , {"label":"8","tag":"value8"} , {"label":"9","tag":"value9"} ] 
 --%>
<%
	String callback=request.getParameter("callback");
	String callbackHeader="";
	String callbackFooter="";
	if(callback!=null){
		callbackHeader=callback+"(";
		callbackFooter=");";
	}
%>
<%=callbackHeader%>[
<%
	XMemcachedClientBuilder builder=
		new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));
	MemcachedClient client=builder.build();
	client.setPrimitiveAsString(true);
	
	boolean isFirst=true;
	for(int i=1;i<10;i++){
		String val=client.get(String.valueOf(i));
		if(val==null)continue;
		if(isFirst){
			isFirst=false;
		}else{
%>
,
<%
		}
%>
{"label":"<%=i %>","tag":"<%=val %>"}
<%
	}
%>
]<%=callbackFooter%>

<%
	client.shutdown();
%>
  • sample.html