JavaScript/nodeJS & Ajax & Plugin

node.js로 구현한 jqGrid 코드

유혁스쿨 2022. 1. 11. 11:11
728x90
반응형

jqGrid HTML + 스크립트 코드

<!DOCTYPE html>
<html>
<head>
<title>jqGrid</title>
<script src="/js/jquery-1.7.2.min.js"></script>
<link href="/css/ui-darkness/jquery-ui-1.10.4.custom.css" rel="stylesheet">
<link href="/css/ui.jqgrid.css" rel="stylesheet" />
<script src="/js/i18n/grid.locale-kr.js"></script>
<script src="/js/jquery.jqGrid.src.js"></script>
<script>
    $(document).ready(function(){
        var customDialog = {
            onclickSubmit : function(params) {
                console.log(params)
                var selectedRow = $('#grid').getGridParam('selrow');
                rowData = $('#grid').getRowData(selectedRow);
                return {id: rowData.id};
            }
        }
		 
        $('#grid').jqGrid({
              url : '/books/get'
            , editurl : '/books/edit'
            , pager : '#pager'
            , datatype : 'json'
            , caption : 'Books'
            , height : '100%'
            , rowNum : 10
            , rowList : [10, 20, 30]
            , colNames : ['id', 'name', 'author', 'publisher', 'isbn', 'page']
            , colModel : [
                  {name : 'id', index : 'id', width : 30}
                , {name : 'name', index : 'name', width : 270, editable :true, edittype: 'text'}
                , {name : 'author', index : 'author', width : 90, align : 'right', editable :true, edittype: 'textarea'}
                , {name : 'publisher', index : 'publisher', width : 80, editable :true, edittype: 'password'}
                , {name : 'isbn', index : 'isbn', width : 80, editable :true, edittype: 'checkbox'}
                , {name : 'page', index : 'page', width : 40, editable :true, edittype: 'file'}
            ]
            , ondblClickRow : function(rowid, row, col, event){
                $('#grid').editGridRow(rowid);
            }
        }).navGrid('#pager',{
              search: true
            , edit : true
            , add : true
            , del : true
        }, customDialog, {}, customDialog);
    }) 
</script> 
</head>
<body>
    <table id="grid"></table>
    <div id="pager"></div>
</body>
</html>

 

 

node.js 스크립트 코드

//모듈 추출
var http = require('http');
var express = require('express'); //express모듈 : http모듈처럼 사용할 수 있지만 훨씬 더 많은 기능이 있는 외부모듈이다.
//http에 http모듈을 추출하여 저장한다. express에 express모듈을 추출하여 저장한다.
var bodyParser = require('body-parser')

var _ = require('underscore');
var array = [];
for(var i = 0; i < 10; i++){
	array[i] = {
		id : i,
		value : i * i
	};
}

var output = _.filter(array, function(item){
	return item.value < 50;
});
console.log('filter',output);

var output = _.reject(array, function(item){
	return item.value < 50;
});
console.log('reject',output);

var output = _.map(array, function(item){
	return item.id + ':' +item.value;
})
console.log('map',output);

var output = _.find(array, function(item){
	return item.id==5;
})
console.log('find',output);

var output = _.sortBy(array, function(item){
	return item.id;
}).reverse();
console.log('sortBy',output); 


var books = [{
	  id: 1
	, name : '모던 웹 디자인을 위한 HTML5 + css3 입문'
	, author : '윤인성'
	, isbn: '9788979149555'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 2
	, name : '모던 웹을 위한 JavaScript + jQuery 입문'
	, author : '윤인성'
	, isbn: '9788979148749'
	, page: 800
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 3
	, name : '모던 웹을 위한 Node.js 프로그래밍'
	, author : '윤인성'
	, isbn: '9788979148886'
	, page: 384
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 4
	, name : '모던 웹을 위한 HTML5 웹소켓 프로그래밍'
	, author : '바네사 왕, 프랭크 실바'
	, isbn: '9788979140317'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 5
	, name : '모던 웹을 위한 실시간 사용자 경험(UX)프로그래밍'
	, author : '테드 로댄'
	, isbn: '9788979149159'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 6
	, name : '만들면서 배우는 codeIgniter 프레임워크'
	, author : '변종월'
	, isbn: '9788979140263'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 7
	, name : '만들면서 배우는 HTML5 + CSS3 + jQuery'
	, author : '야무'
	, isbn: '9788979149104'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 8
	, name : '만들면서 배우는 HTML5 게임 프로그래밍'
	, author : '황동윤'
	, isbn: '9788979140225'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 9
	, name : '만들면서 배우는 기계 학습'
	, author : '오다카 토모히로'
	, isbn: '9788979149234'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
	}
	, {
	  id: 10
	, name : '모던 웹 디자인을 위한 HTML5 + css3 입문'
	, author : '윤인성'
	, isbn: '9788979149555'
	, page: 600
	, publishDate: new Date(2012, 8, 5)
}];

//웹 서버 생성
var app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

//books (jqGrid)
app.get('/books/get', function(request, response){
	console.log('들어왔다!')
	var output = null;
	
	var sidx = request.param('sidx');
	if(sidx == ''){
		sidx = 'id'; //아무값도 없다면 id를 설정한다. id를 기준으로 정렬하게된다.
	}
	console.log('sidx',sidx)
	output = _.sortBy(books, function(item){
		return item[sidx];
	});
	
	var sord = request.param('sord');
	if(sord == 'desc'){
		output = output.reverse();
	}
	//_search 처리
	var _search = request.param('_search');
	if(_search == 'true') {
		var searchField = request.param('searchField');
		var searchString = request.param('searchString');
		output = _.filter(output, function(item){
			if(searchField == 'id'){
				return item.id == Number(searchString);
			}else{
				return item[searchField].indexOf(searchString) != -1;
			}
		});
	}


	var page = Number(request.param('page'));
	var rows = Number(request.param('rows'));
	var totalRecords = books.length;
	var totalPages = Math.ceil(totalRecords / rows);
	var start = rows * page - rows;
	
	output = output.slice(start, start+rows)
	console.log(page, totalPages, totalRecords , _.map(output, function(item){
			return {
				  id : item.id
				, cell : _.toArray(item)
			}
		}))
	
	var param = {
		page : page
		, total : totalPages
		, records : totalRecords
		, rows: _.map(output, function(item){
			return {
				id : item.id
				, cell : _.toArray(item)
			}
		})
	}
	
	response.send(param)
})
app.post('/books/edit', function(request, response){
	switch (request.param('oper')){
		case 'add' :
			books.push({
				id: books.length + 1
				, name : request.param('name')
				, author : request.param('author')
				, publisher : request.param('publisher')
				, isbn : request.param('isbn')
				, page : request.param('page')
			})
			break;
		case 'del' :
			var id = Number(reqeust.param('id'));
			books = _.reject(books, function(item){
				return item.id == id; //books.id가 파라미터로 넘겨받은 id와 일치하는 조건
			})
			break;
		case 'edit' :
			var id = Number(reqeust.param('id'));
			book = _.find(books, function(item){
				return item.id == id;
			})//books.id와 파라미터로 넘겨받은 id와 일치하는 요소를 찾아 book 이름으로 저장.
			book.name = request.param('name')
			book.author = request.param('author')
			book.publisher = request.param('publisher')
			book.isbn = request.param('isbn')
			book.page = request.param('page')
			break;
	}
	response.send();
})

 

728x90
반응형