공부한것들을 정리하는 블로그 입니다.
jqgrid 사용하기 + Daum 오픈 API 검색기능 적용 본문
170707
현재 추가 공부 및 간단한 프로젝트로 더 구현중
다음주부터 추가로 내용 수정 될 예정
---------------------------------------------------------------------------------
jqgrid의 사용방법을 익히기 위해
다음의 4단계를 진행하도록 하겠습니다.
1. jsp상으로 jqgid 적용시켜보기(출력할 데이터는 javascript에서 json파일로 만들어 줌)
2. jsp상으로 Daum 오픈 API 검색기능 적용시켜 보기
3. 상기 두 기능을 합침 : jsp상으로 Daum 오픈 API 검색기능으로 데이터를 불러와서 jqgrid상으로 출력
4. 실제 프로젝트에서 사용해보기(Spring이나 Servlet, 비즈니스 로직과의 결합 등)
* 4번째 단계는 View단도 만들어야 되는 관계로.. 이번 글에서는 다루지 않습니다. 추후에 시간을 내어 포스팅해보도록 하겠습니다.
참고 :
- http://trirand.com/blog/jqgrid/jqgrid.html : JQ그리드 참조문서
- http://blog.naver.com/PostView.nhn?blogId=dalki0126&logNo=220505893629&parentCategoryNo=6&categoryNo=&viewDate=&isShowPopularPosts=true&from=search : 심플하게 객체에 데이터를 담고 jqgrid
- http://roqkffhwk.tistory.com/43 : 심플하게 객체에 데이터를 담고 jqgrid
- http://pjsprogram.tistory.com/3 : spring + jqgrid + json예제
- http://marobiana.tistory.com/26 : spring 환경에서 jqgrid 사용
- http://jhoonslife.tistory.com/532 : 설치 방법 + jqgrid 가이드 + Daum Api 적용 예시 (주의 : 옛날 버젼이라서 다음 개발자센터 관련 값들도 전부 옛날거.. 그래서 그냥 copy & paste하면 적용 안될거임 : 내 코드는 최신으로 개선한 것들임)
- http://blog.naver.com/jaeik714/140185825908 : JQ그리드의 다양한 옵션들을 자세히 설명
- http://pjh3749.tistory.com/154 : JQ그리드 전자정부프레임워크에 적용하기
---------------------------------------------------------------------------------
workspace 주소(검토중)
---------------------------------------------------------------------------------
1. jsp상으로 jqgid 적용시켜보기(출력할 데이터는 javascript에서 json파일로 만들어 줌)
먼저 jqgrid를 사용하기 위해서는 jqgrind / jquery-ui / jquery 이 3가지 라이브러리가 필요합니다.
jqGrid 다운로드
http://www.trirand.com/blog/?page_id=6
jqGrid API 문서겸 데모페이지
http://trirand.com/blog/jqgrid/jqgrid.html
jQueryUI 테마다운로드 페이지
http://jqueryui.com/themeroller/
주소에 들어가서 최신버젼으로 다운로드 받는걸 권장드립니다.
혹시 해당 주소에 접속하기 힘든분을 위해 다운로드 받은 파일도 올려드리겠습니다.
jqgrid 최신버젼(풀버젼)
jqgrid 약간 예전버젼(2017/06 기준으로 가장 신뢰도 높은 버젼 + 좀 더 라이트한 버젼)
jqgrind 알집파일을 두개 업로드 해 드렸는데, 어느 쪽을 사용하시던 상관없습니다(둘 다 문제없이 적용되는것을 직접 확인했습니다. * 단, jquery만은 최신버젼을 쓰시기 바랍니다.).
혹시나 이것조차 힘드신 분들을 위해서 workspace의 WebContent도 첨부하니, 혹시 경로 설정에 문제가 있으신 분들도 참고 바랍니다.
TestJqgrid의 Webcontent
1번 예제
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <link href="resources/jquery-ui/jquery-ui.css" rel="stylesheet" type="text/css" /> <link href="resources/jqGrid/css/ui.jqgrid.css" rel="stylesheet" type="text/css" /> <script src="resources/jqGrid/js/jquery-1.11.0.min.js"></script> <script src="resources/jquery-ui/jquery-ui.js"></script> <%-- <script src="<c:url value="/resources/js/jquery.layout.js"/>"></script> --%> <script src="resources/jqGrid/js/i18n/grid.locale-kr.js"></script> <script src="resources/jqGrid/js/jquery.jqGrid.min.js"></script> <body> <h1>1. jsp상으로 jqgid 적용시켜보기(출력할 데이터는 javascript에서 json파일로 만들어 줌)</h1> <h2>객체를 선언하여 특정 데이터를 넣은 후 jqgrid를 이용해 출력</h2> <table id="list"></table> <script type="text/javascript"> $(function() { $("#list").jqGrid({ datatype : "local", height : 250, colNames : [ '컬럼1', '컬럼2' ], colModel : [ { name : 'col1', index : 'col1' }, { name : 'col2', index : 'col2' }, ], caption : "그리드 배열 데이터 샘플링" }); var mydata = [ { col1 : "내용1", col2 : "내용11" }, { col1 : "내용2", col2 : "내용22" }, ]; //배열을 반복문으로 돌려서 그리드에 add 시킨다 for (var i = 0; i <= mydata.length; i++) { $("#list").jqGrid('addRowData', i + 1, mydata[i]); } }) </script>
1번예제 실행화면
2번 예제
<br> <br> <br> <hr> <h1>1. jsp상으로 jqgid 적용시켜보기(출력할 데이터는 javascript에서 json파일로 만들어 줌)</h1> <h2>객체에 더 많은 조건을 가진, 더 많은 데이터를 넣고 출력 확인</h2> <table id="list4"></table> <script type="text/javascript"> $(function() { // 변수 선언 var i, max, myData, grid = $("#list4"); // grid 설정 grid.jqGrid({ datatype : "local", height : 'auto', colNames : [ 'Inv No', 'Date', 'Client', 'Amount', 'Tax', 'Total', 'Notes' ], colModel : [ { name : 'id', index : 'id', width : 60, sorttype : "int" }, { name : 'invdate', index : 'invdate', width : 90, sorttype : "date" }, { name : 'name', index : 'name', width : 100 }, { name : 'amount', index : 'amount', width : 80, align : "right", sorttype : "float" }, { name : 'tax', index : 'tax', width : 80, align : "right", sorttype : "float" }, { name : 'total', index : 'total', width : 80, align : "right", sorttype : "float" }, { name : 'note', index : 'note', width : 150, sortable : false } ], multiselect : true, caption : "Manipulating Array Data" }); // 로컬 데이터 myData = [ { id : "1", invdate : "2007-10-01", name : "test", note : "note", amount : "200.00", tax : "10.00", total : "210.00" }, { id : "2", invdate : "2007-10-02", name : "test2", note : "note2", amount : "300.00", tax : "20.00", total : "320.00" }, { id : "3", invdate : "2007-09-01", name : "test3", note : "note3", amount : "400.00", tax : "30.00", total : "430.00" }, { id : "4", invdate : "2007-10-04", name : "test", note : "note", amount : "200.00", tax : "10.00", total : "210.00" }, { id : "5", invdate : "2007-10-05", name : "test2", note : "note2", amount : "300.00", tax : "20.00", total : "320.00" }, { id : "6", invdate : "2007-09-06", name : "test3", note : "note3", amount : "400.00", tax : "30.00", total : "430.00" }, { id : "7", invdate : "2007-10-04", name : "test", note : "note", amount : "200.00", tax : "10.00", total : "210.00" }, { id : "8", invdate : "2007-10-03", name : "test2", note : "note2", amount : "300.00", tax : "20.00", total : "320.00" }, { id : "9", invdate : "2007-09-01", name : "test3", note : "note3", amount : "400.00", tax : "30.00", total : "430.00" } ]; // 데이터 추가 for (i = 0, max = myData.length; i <= max; i++) { grid.jqGrid('addRowData', i + 1, myData[i]); } }); </script>
2번예제 실행화면
---------------------------------------------------------------------------------
2. jsp상으로 Daum 오픈 API 검색기능 적용시켜 보기
1번예제
<br> <br> <br> <hr> <h1>2. jsp상으로 Daum 오픈 API 검색기능 적용시켜 보기</h1> <h2>Daum 오픈 API 검색기능1</h2> <h2>이미지검색</h2> 이미지 검색 : <input type="text" id="search"/> <br/> <br/> <br/> <table border="1"> <thead> <tr> <td>이미지</td> </tr> </thead> <tbody id="resultBody"> </tbody> </table> <br/> <br/> <br/> <button onclick="search_image_ajax();">검색</button> <script type="text/javascript"> function search_image_ajax(){ //검색어 var $search = $("#search"); var serchWord = $search.val(); var $resultBody= $("#resultBody"); var url = 'https://apis.daum.net/search/image'; var apiKey = '@'; var urlPath = url+'?'+"apikey="+apiKey; //alert(urlPath); $.ajax({ type : 'POST', url :urlPath+"&q="+serchWord+"&output=json", //도메인 크로스 보안 문제로 json 대신 jsonp로 하자 dataType : 'jsonp', error: function(xhr, status, error){ alert("검색어를 입력해주세요"); }, success : function(json){ //재검색시 tbody의 자식요소들을 모두 제거 $resultBody.empty(); //alert("성공"); //alert("json 객체 : "+jso.channel.item); //넘어온 json 객체있는 item 객체를 담음 var itemIamge = json.channel.item; //alert("아이템 사진 객체 : "+JSON.stringify(itemIamge)); //여기서 원하는 item의 정보를 얻어옴. for(var i = 0 ; i < itemIamge.length; i ++){ //alert("test"); //검색시 나타날 이미지와 링크 var img = "<tr><td><a href='"+itemIamge[i].link+"'><img width='100' height='100' src='"+itemIamge[i].image+"'></a></td></tr>" //alert(img); //tbody에 하위 요소로 출력하기 $resultBody.append(img); } }//success }); } </script>
1번예제 실행화면
2번예제
<br> <br> <br> <hr> <h1>2. jsp상으로 Daum 오픈 API 검색기능 적용시켜 보기</h1> <h2>Daum 오픈 API 검색기능2</h2> <h2>책 검색</h2> 책 검색 : <input type="text" id="search2_2"/> <br/> <br/> <br/> <table border="1"> <thead> <tr> <th>표지</th> <th>제목</th> <th>저자</th> <th>출판사</th> </tr> </thead> <tbody id="resultBody2_2"> </tbody> </table> <br/> <br/> <br/> <button onclick="search_book_ajax();">검색</button> <script type="text/javascript"> function search_book_ajax(){ //검색어 var $search = $("#search2_2"); var serchWord = $search.val(); var $resultBody= $("#resultBody2_2"); var url = 'https://apis.daum.net/search/book'; var apiKey = '@'; var urlPath = url+'?'+"apikey="+apiKey; //alert(urlPath); $.ajax({ type : 'POST', url :urlPath+"&q="+serchWord+"&output=json", //도메인 크로스 보안 문제로 json 대신 jsonp로 하자 dataType : 'jsonp', error: function(xhr, status, error){ alert("검색어를 입력해주세요"); }, success : function(json){ //재검색시 tbody의 자식요소들을 모두 제거 $resultBody.empty(); //alert("성공"); //alert("json 객체 : "+jso.channel.item); //넘어온 json 객체있는 item 객체를 담음 var itemIamge = json.channel.item; //alert("아이템 사진 객체 : "+JSON.stringify(itemIamge)); //여기서 원하는 item의 정보를 얻어옴. for(var i = 0 ; i < itemIamge.length; i ++){ //alert("test"); //검색시 나타날 정보 + 이미지와 링크 var img = "<tr><td><img width='300' height='300' src='"+itemIamge[i].cover_l_url+"'/></td>" +"<td>"+itemIamge[i].title+"</td>" +"<td>"+itemIamge[i].author+"</td>" +"<td>"+itemIamge[i].pub_nm+"</td></tr>" //alert(img); //tbody에 하위 요소로 출력하기 $resultBody.append(img); } }//success }); } </script>
2번예제 실행화면
---------------------------------------------------------------------------------
3. 상기 두 기능을 합침 : jsp상으로 Daum 오픈 API 검색기능으로 데이터를 불러와서 jqgrid상으로 출력
<br> <br> <br> <hr> <h1>3. 상기 두 기능을 합침 : jsp상으로 Daum 오픈 API 검색기능으로 데이터를 불러와서 jqgrid상으로 출력</h1> <h2>jqgrid + Daum 오픈 API 검색기능 </h2> <h5>테스트용 코드이기에, 현재 "책검색:다음카카오"로 3개의 파일를 4페이지 분량으로 받음 </h5> <h5>>>버튼을 누르면 기존에 받아온 데이터가 출력됨 </h5> <h6>* 번외 : 3개의 파일를 4페이지 분량으로 받음 - 배열로 받는것이기 때문에 설정해둔 값 이상은 받아오지 않음 : 배열을 동적할당하여 받아오도록 심화학습 해보자(http://mwultong.blogspot.com/2006/11/java-array-resize-dynamic-array.html, http://dhddl.tistory.com/entry/JAVA-%EC%9E%90%EB%B0%94%EC%9D%98-Array%EB%B0%B0%EC%97%B4-%EB%8F%99%EC%A0%81%ED%95%A0%EB%8B%B9) </h6> jqGrid 플러그인을 사하기위한 table 태그와 div태그 사용 <table id = "grid"></table> <div id = "pager"></div> <script type="text/javascript"> $(window.document).ready(function() { $("#grid").jqGrid({ url : 'https://apis.daum.net/search/book?apikey=@&q=다음카카오&output=json', caption : 'Daum SNS Pic', // caption : 그리드의 제목을 지정한다. datatype : 'jsonp', // datatype : 데이터 타입을 지정한다. // (json 으로 외부에 요청을 보내면 보안정책에 위배되어 요청이 나가질 않는다. // 따라서 datatype 을 jsonp로 변경하고 보내야 한다.) mtype : 'get', // mtype : 데이터 전송방식을 지정한다. height : '150px', // height : 그리드의 높이를 지정한다. pager : '#pager', // pager : 도구 모임이 될 div 태그를 지정한다. rowNum : 3, // rowNum : 한 화면에 표시할 행 개수를 지정한다. loadonce : true, // loadonce : rowNum 설정을 사용하기 위해서 true로 지정한다. rowList : [3, 6, 9, 10], // rowList : rowNum을 선택할 수 있는 옵션을 지정한다. // colNames : 열의 이름을 지정한다. colNames : [ '표지', '제목', '저자', '출판사' ], colModel : [ { name : 'cover_l_url', index : 'cover_l_url', width : 100, align : 'center' }, { name : 'title', index : 'title', width : 100, align : 'center' }, { name : 'author', index : 'author', width : 100, align : 'center' }, { name : 'pub_nm', index : 'pub_nm', width : 100, align : 'center' } ], // jqGrid 에서 default 형태의 JSON 이 아닌 소셜픽만의 고유의 json 형태로 날아오기에. // 소셜픽의 API 를 바꿀 순 없어, jqGrid 에서 json을 // customizing하여 사용하기 위해 jsonReader를 사용했다. jsonReader : { repeatitems : false, id : "cover_l_url", root : function (obj) { return obj.channel.item; }, page : function (obj) { return 1; }, total : function (obj) { return 1; }, records : function (obj) {return obj.channel.item.length; } } // navGrid() 메서드는 검색 및 기타기능을 사용하기위해 사용된다. }).navGrid('#pager', { search : true, edit : true, add : true, del : true }); }); </script> </body> </html>
1번예제 실행화면
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel = "stylesheet" type = "text/css" media = "screen" href = "css/jquery-ui-1.10.3.custom.min.css"/> <link rel = "stylesheet" type = "text/css" media = "screen" href = "css/ui.jqgrid.css"/> <script src = "js/jquery-1.11.0.min.js" type = "text/javascript"></script> <!-- <script src = "js/jquery-1.9.0.min.js" type = "text/javascript"></script> --> <script src = "js/i18n/grid.locale-kr.js" type = "text/javascript"></script> <script src = "js/jquery.jqGrid.min.js" type = "text/javascript"></script> <!-- <script> $(window.document).ready(function() { $("#grid").jqGrid({ url : 'https://apis.daum.net/search/book?apikey={@}&q=다음카카오&output=json', caption : 'Daum SNS Pic', // caption : 그리드의 제목을 지정한다. datatype : 'jsonp', // datatype : 데이터 타입을 지정한다. // (json 으로 외부에 요청을 보내면 보안정책에 위배되어 요청이 나가질 않는다. // 따라서 datatype 을 jsonp로 변경하고 보내야 한다.) mtype : 'get', // mtype : 데이터 전송방식을 지정한다. height : '500px', // height : 그리드의 높이를 지정한다. pager : '#pager', // pager : 도구 모임이 될 div 태그를 지정한다. rowNum : 3, // rowNum : 한 화면에 표시할 행 개수를 지정한다. loadonce : true, // loadonce : rowNum 설정을 사용하기 위해서 true로 지정한다. rowList : [3, 6, 9, 10], // rowList : rowNum을 선택할 수 있는 옵션을 지정한다. // colNames : 열의 이름을 지정한다. colNames : [ '순위', '소셜픽키워드', '이슈에 대한 링크 URL', '요약문', '검색수', '트윗수', '검색 결과의 페이지 번호', '순위 상승/하락수', '카테고리' ], colModel : [ { name : 'rank', index : 'rank', width : 40, align : 'center' }, { name : 'keyword', index : 'keyword', width : 100, align : 'left' }, { name : 'link', index : 'link', width : 100, align : 'left' }, { name : 'content', index : 'content', width : 200, align : 'left' }, { name : 'count', index : 'count', width : 100, align : 'center' }, { name : 'quotation_cnt', index : 'quotation_cnt', width : 100, align : 'center' }, { name : 'comment_cnt', index : 'comment_cnt', width : 100, align : 'center' }, { name : 'rank_diff', index : 'rank_diff', width : 100, align : 'center' }, { name : 'category', index : 'category', width : 100, align : 'center' } ], // jqGrid 에서 default 형태의 JSON 이 아닌 소셜픽만의 고유의 json 형태로 날아오기에. // 소셜픽의 API 를 바꿀 순 없어, jqGrid 에서 json을 // customizing하여 사용하기 위해 jsonReader를 사용했다. jsonReader : { repeatitems : false, id : "rank", root : function (obj) { return obj.socialpick.item; }, page : function (obj) { return 1; }, total : function (obj) { return 1; }, records : function (obj) {return obj.socialpick.item.length; } } // navGrid() 메서드는 검색 및 기타기능을 사용하기위해 사용된다. }).navGrid('#pager', { search : true, edit : true, add : true, del : true }); }); </script>--> <title>jqGrid</title> </head> <body style = "font-size:62.5%;"> <h1>3. 상기 두 기능을 합침 : jsp상으로 Daum 오픈 API 검색기능으로 데이터를 불러와서 jqgrid상으로 출력</h1> <h2>jqgrid + Daum 오픈 API 검색기능 </h2> <h5>테스트용 코드이기에, 현재 "책검색:정의"로 3개의 파일를 4페이지 분량으로 받음 </h5> <h5>>>버튼을 누르면 기존에 받아온 데이터가 출력됨 </h5> <div class="row"> <div> <table id = "grid"></table> <div id = "pager"></div> </div> </div> <script type="text/javascript"> $(window.document).ready(function() { $("#grid").jqGrid({ url : 'https://apis.daum.net/search/book?apikey=@&result=12&q=정의&output=json', caption : 'Daum SNS Pic', // caption : 그리드의 제목을 지정한다. datatype : 'jsonp', // datatype : 데이터 타입을 지정한다. // (json 으로 외부에 요청을 보내면 보안정책에 위배되어 요청이 나가질 않는다. // 따라서 datatype 을 jsonp로 변경하고 보내야 한다.) mtype : 'get', // mtype : 데이터 전송방식을 지정한다. // height : '500px', // height : 그리드의 높이를 지정한다. height : 'auto', // height : 그리드의 높이를 지정한다. pager : '#pager', // pager : 도구 모임이 될 div 태그를 지정한다. rownumbers : true, viewrecords : true, rowNum : 3, // rowNum : 한 화면에 표시할 행 개수를 지정한다. loadonce : true, // loadonce : rowNum 설정을 사용하기 위해서 true로 지정한다. rowList : [3, 6, 9, 12], // rowList : rowNum을 선택할 수 있는 옵션을 지정한다. // colNames : 열의 이름을 지정한다. colNames : [ '카테고리', '제목', '저자', '출판사' ], colModel : [ { name : 'category', index : 'category', width : 100, align : 'center' }, { name : 'title', index : 'title', width : 300, align : 'center' }, { name : 'author', index : 'author', width : 100, align : 'center' }, { name : 'pub_nm', index : 'pub_nm', width : 100, align : 'center' } ], // jqGrid 에서 default 형태의 JSON 이 아닌 소셜픽만의 고유의 json 형태로 날아오기에. // 소셜픽의 API 를 바꿀 순 없어, jqGrid 에서 json을 // customizing하여 사용하기 위해 jsonReader를 사용했다. jsonReader : { repeatitems : false, id : "category", root : function (obj) { return obj.channel.item; }, page : function (obj) { return 1; }, total : function (obj) { return 1; }, records : function (obj) {return obj.channel.item.length; } } // navGrid() 메서드는 검색 및 기타기능을 사용하기위해 사용된다. }).navGrid('#pager', { search : true, edit : true, add : true, del : true }); }); </script> </body> </html>
'JQ그리드 공부' 카테고리의 다른 글
jqgrid Array 데이터 불러오기 + Multi Select 다중선택 (선택된 행의 ID 보기 + 특정 행 선택하기/선택풀기) (0) | 2017.08.02 |
---|---|
jqgrid XML 데이터 불러오기 (0) | 2017.08.02 |
jqgrid workspace (0) | 2017.06.27 |