반응형

1. CDN 추가

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.5/xlsx.full.min.js"></script>

 

2. 엑셀 읽는 함수 소스

document.getElementById("serialFile").onchange = function(){
	const file = event.target.files[0];
	const reader = new FileReader();
	reader.onload = () => {
		const data = reader.result;
		const workBook = XLSX.read(data, { type: 'binary' });
		//workBook.SheetNames : 엑셀파일의 시트이름이 배열로 담김
		workBook.SheetNames.forEach(sheetName => {
			//row : 엑셀의 한 행이 json으로 추출됨
			const row = XLSX.utils.sheet_to_json(workBook.Sheets[sheetName]);
		})
	};
	reader.readAsBinaryString(file);
}

 

 

반응형
반응형

datepicker에 필요한 파일

// jquery.js, jquery-ui.css , jquery-ui.js
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

 

 

datepicker 기본 세팅(세팅 후 dom에 붙이는 경우)

//datepicker의 기본옵션을 설정
$.datepicker.setDefaults({
  //날짜 포맷, 실제 데이터 포맷은 yyyy/mm/dd
  dateFormat: "yy/mm/dd",
  
  //prev 아이콘 마우스오버 표시 텍스트
  prevText: "이전 달",
  
  //next 아이콘 마우스오버 표시 텍스트
  nextText: "다음 달",	
  
  //달력에 표시될 월 이름
  monthNames: ["1월", "2월", "3월", "4월", "5월", "6월","7월", "8월", "9월", "10월", "11월", "12월",],
  
  //요일 이름(html상 dom title이 되는 듯)
  dayNames: ["일", "월", "화", "수", "목", "금", "토"],
  
  //달력에 표시될 요일 이름
  dayNamesMin: ["일", "월", "화", "수", "목", "금", "토"],
  
  //달력에서 연-월 순으로 표시되게 함
  showMonthAfterYear: true,
  
  //달력에서 yyyy뒤에 붙일 단위
  yearSuffix: "년",
  
  //선택 가능한 최소 날짜
  minDate: "2021/07/12",
  
  //선택 가능한 최대 날짜
  maxDate: "2021/08/12",
  
  //월이 텍스트가 아니라 드랍박스(select)형태로 나옴
  changeMonth: true,
  
  //changeMonth를 사용하는 경우 표시될 월 이름 약자
  monthNamesShort: ["1월", "2월", "3월", "4월", "5월", "6월","7월", "8월", "9월", "10월", "11월", "12월",],
  
  //년도가 텍스트가 아니라 드랍박스(select)형태로 나옴
  changeYear: true,
  
  //달력 밑에 버튼 표출 여부. 오늘 날짜 설정하는 today 버튼과 완료(done)버튼이 표시가 됨.
  showButtonPanel : treu,
  
  //날짜가 선택되면 호출될 함수
  onSelect: function (dateText) {
    console.log(dateText)
  },
  
  //년이나 월 변경시에 호출될 함수
  onChangeMonthYear : function (year,month){
    console.log(year + '년 ' + month);
  },
  
  //달력이 표시되기 전에 호출될 함수
  beforeShow: function () {
    alert("날짜 선택");
  },
});

 

dom 객체에 datepicker 붙이기 

$("#startDt").datepicker();
$("#endDt").datepicker();

 

세팅과 동시에 dom에 붙이는 방법도 있다.

$("#endDt").datepicker({
    dateFormat: "yy/mm/dd",
    onSelect: function (dateText) {
    },
}).datepicker("setDate",new Date());

 

 

메소드 사용하기

// 메소드 기본 사용 형태
$( ".selector" ).datepicker( "메소드이름", 파라미터);
//달력에 표시할 기본 날짜를 지정하는 메소드
$( ".selector" ).datepicker( "setDate", new Date());
$( ".selector" ).datepicker( "setDate", "2021/08/11");

//옵션을 설정하는 메소드
 $("#endDt").datepicker("option", {
        minDate: "2021/07/11",
        beforeShow: function () {
		},
 });

 

반응형
반응형
let content = null;
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/static/file/파일이름", false);
xmlhttp.send();
//파일 로드 성공 시 파일에서 읽은 텍스트를 content에 담음
if (xmlhttp.status == 200) { 
  content = xmlhttp.responseText;
}
console.log(content);
반응형
반응형
반응형
반응형

fetch 사용해보기


fetch() 기본

//fetch를 호출하면 브라우저는 네트워크 요청을 보내고 promise를 반환한다.
let promise = fetch(url, {options})
fetch(url, options)
	//api호출 성공 시 응답(response) 반환
  .then((response) => console.log("response:", response))
	//실패시 error 반환
  .catch((error) => console.log("error:", error));

 

fetch  사용 예시

    fetch("https://localhost:8080/urlurl", {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache', 
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
        },
        redirect: 'follow', 
        referrer: 'no-referrer',
        body: JSON.stringify(obj),
    })//fetch 실행이 끝나면 then의 내용 실행
    //응답을 JSON 형태로 파싱한다
    .then(response => response.json()) 
    .then(function (res){
    
    })

 

응답을 처리할 때 사용하는 메서드

response.text() 응답을 읽고 텍스트를 반환
response.json() 응답을 JSON 형태로 파싱
response.formData() 응답을 FormData 객체 형태로 반환
response.blob() 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 반환
response.arrayBuffer() 응답을 ArrayBuffer(바이너리 데이터를 로우 레벨 형식으로 표현한 것) 형태로 반환

* 본문을 읽을 때 사용되는 메서드는 딱 하나만 사용할 수 있다.

let text = await response.text(); // 응답 본문을 읽고 test를 반환
let parsed = await response.json(); // 실패
반응형
반응형

1. 날짜 구하기

//오늘날짜 구하기
var date = new Date(); 

//년도 구하기.. ex)2022
var year = date.getFullYear(); 

//월 구하기.. 0~11이므로 1을 더해주고 한자리수면 앞에 0을 붙여줌 ex)08
var month = date.getMonth()+1 < 10? "0".concat(date.getMonth()+1) : date.getMonth()+1;

//일 구하기.. ex)11
var day = date.getDate(); 

//결과 : 2022-08-11
$('date').value = year+'-'+month+'-'+day;

 

2. 날짜 계산

var sdate = new Date();
sdate.setDate(sdate.getDate()-31);	
sdate.setMonth(sdate.getMonth()+2);
sdate.setYear(sdate.getYear()-1);

 

 

3. 날짜값 반환하는 함수

Date.prototype 으로 Date함수의 값을 커스텀해서 반환한다.

Date.prototype.myCustom = function () {
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth() + 1).toString();
  var dd = this.getDate().toString();
  var hh = this.getHours().toString();
  var ii = this.getMinutes().toString();
  return (
    yyyy +
    "-" +
    (mm[1] ? mm : "0" + mm[0]) +
    "-" +
    (dd[1] ? dd : "0" + dd[0]) +
    "  " +
    (hh[1] ? hh : "0" + hh[0]) +
    ":" +
    (ii[1] ? ii : "0" + ii[0])
  );
};


//함수 사용하기 
let updateTime = new Date().myCustom();

변수를 출력하면 내가 지정한 형식의 날짜가 표시된다.

 

반응형
반응형

셋 중에 하나를 이용

$('#Iframe').bind('load',function () {

});
$("#Iframe").load(function () {

  });
$("#Iframe").ready(function(){

 });

 

예시

iframe 로딩이 되는 동안 프로그레스 바를 표시,

로딩 완료후 숨김

//로더 표시
$(".loader").show();

//로더 숨김
$("#reportIframe").load(function () {
    $(".loader").hide();
  });
반응형
반응형

test라는 dom에 click이벤트가 걸린 상황.

 

이 경우에 click 이벤트가 중복으로 걸려서 

횟수가 x2 되어 실행된다.

또 누를 경우 x2 되어 4번.. 8번...

중복을 막기위해 .off를 추가해주자 

function func1(){

  $(document).off("click", "#test").on("click", "#test", function () {
    func1();
  });
    
}
반응형
반응형
$("#table").DataTable().destroy(); //이전에 만든 것 없애고 다시 그리기 위함.
const table = $("#table").DataTable({
          responsive: false,  //반응형 설정
          pageLength: 10,     //페이지 당 글 개수 설정
          autoWidth: false,
          destroy: true,
          processing: true,
          serverSide: false,
          searching: false,    //검색란 표시 설정
          ordering: true,      //글 순서 설정
          paging: true,        //페이징 표시 설정
          dom: "Blfrtip",      //버튼 dom 설정 l을 추가하면 pagelength 드롭다운 표시
          buttons: [
            {
              extend: "excel",
              text: "엑셀 다운로드",
              filename: function () {
                if ($("#file1").val() === "a1") {
                  return "_"+$("#file1").val();
                } else {
                  return "file2";
                }
              },

              customize: function (xlsx) {
              //엑셀 셀 커스텀
                var sheet = xlsx.xl.worksheets["sheet1.xml"];
                $("c[r=B2] t", sheet).text("custom text1");
                $("c[r=C2] t", sheet).text("custom text2");
 
              },
            },
          ],
          language: {
            emptyTable: "데이터가 없습니다.",
            lengthMenu: "페이지당 _MENU_ 개씩 보기",
            info: "현재 _START_ - _END_ / _TOTAL_건",
            infoEmpty: "데이터 없음",
            infoFiltered: "( _MAX_건의 데이터에서 필터링됨 )",
            search: "",
            zeroRecords: "일치하는 데이터가 없습니다.",
            loadingRecords: "로딩중...",
            processing: "잠시만 기다려 주세요.",
            paginate: {
              next: "다음",
              previous: "이전",
            },
          },
          data: chartDataList,
          columns: [
            { data: "data1" },
            { data: "data2" },
            { data: "data3" },
            { data: "data4" },
          ],
          columnDefs: [
            {//0번컬럼 설정
              targets: 0,
              orderable : false,
              render: function (data) {
                if ($("#searchType").val() === "day") {
                  return data + "시";
                } else {
                  return data;
                }
              },
            },
            {//1번,2번컬럼 설정
              targets: [1,2],
              visible: false,
              orderable : false,
              render: function (data) {
              	return data;      
              },
            },
            {//모든 컬럼 설정
              targets: "_all",
              render: function (data, type, full, meta) {
              	console.log(data); // 데이터중 해당 열, 행에 들어갈 data
                console.log(type); 
                console.log(full); // 데이터중 해당 행에 들어갈 full data
                console.log(meta); // 해당 셀의 row, col 번호
              },
            },
          ],
        });
        
//데이터 테이블 필터링하여 보여주기 설정
//필터링 할 컬럼 번호로 search 이용
table.column(0).search("value").draw();
반응형
반응형

cannot read property 'substring' of null

cannot read property 'substring' of undefined

 

왜 null이라고 나오는지 모르겠네..

substring 하려는 변수를 ""를 붙여서 string 타입으로 바꿔버리자..

 

let aaa = ""+mydata;

 

반응형

+ Recent posts