이번장의 설명은 json object롤 autocomplete를 만들어 보도록 하겠다
json-simple 다운로드 (json-simple-1.1.1.jar 기준)
이전 포스팅과는 별 다른거 바뀌는건 없고
서버용 테스트 파일 1개추가와 autocomplete.html에서
$( "#autocompleteText" ).autocomplete({}) << 이놈만 변경해보겠다.
우선 autocomplete.html 페이지에 autocomplete 소스만 수정해보자
스크립트코드
$(function(){ $( "#autocompleteText" ).autocomplete({ source : function( request, response ) { //많이 봤죠? jquery Ajax로 비동기 통신한 후 //json객체를 서버에서 내려받아서 리스트 뽑는 작업 $.ajax({ //호출할 URL url: "search.jsp", //우선 jsontype json으로 dataType: "json", // parameter 값이다. 여러개를 줄수도 있다. data: { //request.term >> 이거 자체가 text박스내에 입력된 값이다. searchValue: request.term }, success: function( result ) { //return 된놈을 response() 함수내에 다음과 같이 정의해서 뽑아온다. response( $.map( result, function( item ) { return { //label : 화면에 보여지는 텍스트 //value : 실제 text태그에 들어갈 값 //본인은 둘다 똑같이 줬음 //화면에 보여지는 text가 즉, value가 되기때문 label: item.data, value: item.data } }) ); } }); }, //최소 몇자 이상되면 통신을 시작하겠다라는 옵션 minLength: 2, //자동완성 목록에서 특정 값 선택시 처리하는 동작 구현 //구현없으면 단순 text태그내에 값이 들어간다. select: function( event, ui ) {} }); })
좀 길어졌지만 실질적으로 우리가 아는 $.ajax를 이용한것이다. 주석도 많이 달았고...
그럼 서버처리 부분을 보도록 하자 해당 소스를 php / jsp / spring framework 등등
응용해서 변경하면 될거 같다.
search.jsp 코드
String searchValue = request.getParameter("searchValue"); JSONArray arrayObj=new JSONArray(); JSONObject jsonObj = null; //////////// 임의의 데이터(db라 가정하자) //////////// ArrayList<String> dblist = new ArrayList<String>(); ArrayList<String> resultlist = new ArrayList<String>(); dblist.add("Afghanistan"); dblist.add("Albania"); dblist.add("Algeria"); dblist.add("American"); dblist.add("Samoa"); dblist.add("Andorra"); for(String str : dblist) { if(str.toLowerCase().startsWith(searchValue)) { resultlist.add(str); } } ///////////resultlist를 db에서 조회후 뽑아온 list라고 가정한다./////////// //뽑은 후 json파싱 for(String str : resultlist) { jsonObj = new JSONObject(); jsonObj.put("data", str); arrayObj.add(jsonObj); } PrintWriter pw = response.getWriter(); pw.print(arrayObj); pw.flush(); pw.close();
은근히 길어 보이지만 db라 가정한 arraylist 객체때문에 약간 소스가 길어진거임.
db연동을 하면 해당 담는 부분은 지워서 db호출을 하면 될것임.
모달창을 띄우고 싶다면 jQueryUI의 DIALOG 함수를 이용해보자 (0) | 2014.06.20 |
---|---|
jQueryUI에서 제공하는 Accordion을 이용해보자 (0) | 2014.06.20 |
jQueryUI에서 지원하는 달력 컴포넌트를 이용하여 TEXT태그에 값넣어보기 (0) | 2014.06.19 |
jQueryUI를 이용하여 자동완성기능을 제작해보자 - (1) (0) | 2014.06.19 |
jQueryUI 시작하기 - 다운로드부터 버튼출력까지 (0) | 2014.06.19 |