레이블이 jquery인 게시물을 표시합니다. 모든 게시물 표시
레이블이 jquery인 게시물을 표시합니다. 모든 게시물 표시

2020년 5월 3일 일요일

Cesium에서 canvas 화면 center 지점의 좌표 취득

지도상 현재 위치의 center 지점에 대해서 카메라 이동


var center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
var heading = Cesium.Math.toRadians(230.0);
var pitch = Cesium.Math.toRadians(-20.0);
camera.lookAt(center, new Cesium.HeadingPitchRange(heading, pitch, r * 2.0));
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);

2020년 3월 16일 월요일

모달 띄우는 코드

모달 띄우기

html 코드로 모달 띄우기

<!--모달 띄우기 버튼-->
<a href="javascript:void(0)" class="btn btn-download" data-toggle="modal" data-target="#downloadModal">GML Download</a>
<!--모달 창 디자인-->
<div class="modal inmodal fade" id="downloadModal" tabindex="-1" role="dialog"  aria-hidden="true">
    <div class="modal-dialog modal-download">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
					<span aria-hidden="true">×</span>
					<span class="sr-only">Close</span>
				</button>
                <h5 class="modal-title">
                    Download
                </h5>
            </div>
            <div class="modal-body">
                <form class="d-inline" action="<c:url value="/"/>downloadGML.do" method="POST">
                    <input type="hidden" name="taodSeq" value="" />
                    <input type="hidden" name="gmlType" value="" />
                    <button type="button" class="btn fov-down">Geo Cultural Contents</button>
                    <button type="button" class="btn boun-down">Geo Referenced Contents</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

자바스크립트로 모달 띄우기

<!--모달 띄우기 버튼-->
<a href="javascript:void(0)" class="btn btn-download">GML Download</a>
/**
 * 모달 띄우기 스크립트
 */
$('.download-gml').click(function() {
    event.preventDefault(); //태그의 기본 동작 차단

    //{backdrop: 'static'}는 여백 클릭시 닫히지 않도록 하는 옵션
    $('#downloadModal').modal({backdrop: 'static'}).on('shown.bs.modal', function (e){
        console.info('download modal');
    });
});
<!--모달 창 디자인-->
<div class="modal inmodal fade" id="downloadModal" tabindex="-1" role="dialog"  aria-hidden="true">
    <div class="modal-dialog modal-download">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
					<span aria-hidden="true">×</span>
					<span class="sr-only">Close</span>
				</button>
                <h5 class="modal-title">
                    Download
                </h5>
            </div>
            <div class="modal-body">
                <form class="d-inline" action="<c:url value="/"/>downloadGML.do" method="POST">
                    <input type="hidden" name="taodSeq" value="" />
                    <input type="hidden" name="gmlType" value="" />
                    <button type="button" class="btn fov-down">Geo Cultural Contents</button>
                    <button type="button" class="btn boun-down">Geo Referenced Contents</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

2018년 12월 27일 목요일

javascript, jQuery에서 루프(loop) 돌리기 예 (for, forEach, each)

javascript for문 사용 예

//예문1) 미지원 브라우저 없음
for (var i=0; i<array.length; i++) {
    console.log(array[i]);
}

//예문2.1) ie8 이하 미지원
for (var i in array) {
    console.log(array[i]);
}

//예문2.2) object형 변수의 루프 돌리기
var viewModel = {
    entity : undefined,
    longitude: 127.33887522,
    latitude: 36.34803794,
    height: 0,
    heading: 0,
    pitch: 0,
    roll: 0
};
for (var name in viewModel) {
    console.log(name + ": " + viewModel[name]);
}

//예문3.1) ie9, ff1.5 미만 미지원
array.forEach(function(currentValue, index, arr), thisValue);

//예문3.2) ie9, ff1.5 미만 미지원
var numbers = [65, 44, 12, 4];
function myFunction(item, index, arr) {}
numbers.forEach(myFunction);

jQuery 루프문 사용 예

//예문1)
$("li").each(function(index) {
    console.log(index + ": " + $(this).text());
});

//예문2)
$("div").each(function(index, element) {
    //$(element) == $(this)
    $(element).css("color", "yellow");
    if ($(this).is("#stop")) {
        $("span").text("index : " + index);

        //continue : return true;
        //break : return false;
        return false;
    }
});

//예문3)
var result = {
    navigationList : {
        "0": {
            "coordinatex" : "126",
            "coordinatey" : "36",
        },
        "1": {
            "coordinatex" : "126",
            "coordinatey" : "36",
        }
    }
};
$.each(result.navigationList, function(idx, data) {
    console.log('for:',data.coordinatex, data.coordinatey);
});

//예문4)
var obj = {
    "a": "1",
    "b": "2"
};
$.each(obj, function(key, value) {
    alert(key + ": " + value);
});

//예문5)
$.each([52, 97], function(index, value) {
    alert(index + ": " + value);
});

//예문6)
const obj = { a: 1, b: 2, c: 3 };

for (const key in obj) {
  if (obj.hasOwnProperty(key)) { // 객체의 고유 속성만 확인
    console.log(key, obj[key]);
  }
}

//예문7)
const obj = { a: 1, b: 2, c: 3 };

Object.keys(obj).forEach(key => {
  console.log(key, obj[key]);
});

//예문8)
const obj = { a: 1, b: 2, c: 3 };

Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value);
});

//예문9)
const obj = { a: 1, b: 2, c: 3 };

Object.values(obj).forEach(value => {
  console.log(value);
});

//예문10)
const obj = { a: 1, b: 2, c: 3 };

for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}

//예문11)
const obj = { a: 1, b: 2, c: 3 };

for (const key of Object.keys(obj)) {
  console.log(key, obj[key]);
}

//예문12)

2018년 10월 3일 수요일

jQuery 사용자 정의 속성이 잘 반영되지 않은 경우

jQuery 사용 중 사용자 정의 속성이 잘 반영되지 않는 경우가 있어 정리해 보았다.

<div id="modifyGeo">test</div>
위와 같은 HTML에 JQuery를 이용해서 사용자 정의 속성을 정의하고 값을 세팅하였다.
값은 여러번 재 세팅하고 필요할때 값을 읽어서 활용하려 하였다.

$('#modifyGeo').attr('data-idx',idx);
console.log($('#modifyGeo').data('idx')));
이렇게 사용했을때 최초 한번은 잘 세팅 되었지만 이후에 세팅한 값은 불러올 수 없었다.

$('#modifyGeo').data('idx',idx);
console.log($('#modifyGeo').data('idx')));
이렇게 사용시 매번 세팅한 값을 잘 읽어올 수 있었다.

2018년 2월 20일 화요일

자바스크립트에서 이벤트 전파 중단 하는 방법

자바스크립트에서 이벤트 수행 막기


event.preventDefault()

현재 요소에 직접 걸어준 이벤트는 처리하지만 태그의 기본 동작은 작동하지 않도록 막는다.


event.stopPropagation()

기본적으로 하위 요소에서 발생한 이벤트는 상위 요소에서도 캐치가 가능한데 이 함수는 현재 요소에서 발생한 이벤트가 상위 요소에서는 발생하지 않도록 막아준다.


event.stopImmediatePropagation()

현재 요소에 발생한 이벤트가 상위 요소에서 발생하지 않도록 막아주고, 현재 요소의 이벤트가 여럿일 경우 첫 번째 정의한 이벤트만 작동하도록 한다.


return false

jQuery에서 : event.preventDefault()와 event.stopPropagation() 동시 수행한다.
javascript에서 : event.preventDefault()와 같다.
ex) <a href="javascript:return false;">링크예시<a>



예제 소스

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
nav {background-color: gray; padding: 40px;}
div {background-color: yellow; padding: 40px;}
a {background-color: green; padding: 20px; display: inline-block;}
</style>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function(){
    $("div").on("click",function() {
        console.log("div 태그의 클릭 이벤트");
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트1");
        event.preventDefault();
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트2");
        event.preventDefault();
    });
});
</script>
</head>
<body>
<nav>
    <div>
        <a href="http://www.daum.net" target="_blank">링크</a>
        <a href="javascript:console.log('a 태그의 인라인 자바스크립트 호출');">alert</a>
    </div>
</nav>
</body>
</html>


event.preventDefault()

$(function(){
    $("div").on("click",function() {
        console.log("div 태그의 클릭 이벤트");
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트1");
        event.preventDefault();
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트2");
        event.preventDefault();
    });
});

스크립트 부분을 위 처럼 작성 후


1. <a> 클릭시
  - a 태그의 링크 기능이 작동하지 않는다
  - a 태그의 인라인 자바스크립트가 작동하지 않는다.
  - a 태그에 걸어둔 2개의 이벤트가 모두 작동한다.
  - 부모 요소인 div 태그에 걸어둔 이벤트도 함께 작동한다.

2. <div> 클릭시
  - div 태그에 걸어둔 이벤트만 작동한다.

3. <nav> 클릭시
  - 아무런 작동이 없다.


event.stopPropagation()

$(function(){
    $("div").on("click",function() {
        console.log("div 태그의 클릭 이벤트");
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트1");
        event.stopPropagation();
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트2");
        event.stopPropagation();
    });
});

위 처럼 스크립트 사용시 자식 요소에서 클릭 이벤트가 발생하더라도 부모 요소에 걸어둔 이벤트는 작동하지 않았다.

스크립트 부분을 위 처럼 작성 후


1. <a> 클릭시
  - a 태그의 링크 기능이 정상 작동한다
  - a 태그의 인라인 자바스크립트가 정상 작동한다.
  - a 태그에 걸어둔 2개의 이벤트가 모두 작동하였다.
  - 부모 요소인 div 태그에 걸어둔 이벤트는 작동하지 않는다.

2. <div> 클릭시
  - div 태그에 걸어둔 이벤트만 작동한다.

3. <nav> 클릭시
  - 아무런 작동이 없다.


event.stopImmediatePropagation()

$(function(){
    $("div").on("click",function() {
        console.log("div 태그의 클릭 이벤트");
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트1");
        event.stopImmediatePropagation();
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트2");
        event.stopImmediatePropagation();
    });
});

위 처럼 스크립트 사용시 여러개의 이벤트 중 첫번째 선언한 이벤트 하나만 처리되었고 인라인 자바스크립트는 정상적으로 실행되는 것을 확인할 수 있었다.

스크립트 부분을 위 처럼 작성 후


1. <a> 클릭시
  - a 태그의 링크 기능이 정상 작동한다
  - a 태그의 인라인 자바스크립트가 정상 작동한다.
  - a 태그에 걸어둔 이벤트 중 먼저 선언한 이벤트 하나만 작동한다.
  - 부모 요소인 div 태그에 걸어둔 이벤트는 작동하지 않는다.

2. <div> 클릭시
  - div 태그에 걸어둔 이벤트만 작동한다.

3. <nav> 클릭시
  - 아무런 작동이 없다.


return false

$(function(){
    $("div").on("click",function() {
        console.log("div 태그의 클릭 이벤트");
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트1");
        return false;
    });
    $("a").on("click",function(event) {
        console.log("a 태그의 클릭 이벤트2");
        return false;
    });
});

위와 같이 return false를 사용하면 event.stopPropagation()과 event.preventDefault()를 동시에 사용하는 것과 같은 작동을 하였다. 태그 원래의 기능과 인라인 자바스크립트의 수행을 막고자 한다면 위처럼 사용해도 될 것 같다.

스크립트 부분을 위 처럼 작성 후


1. <a> 클릭시
  - a 태그의 링크 기능이 작동하지 않는다
  - a 태그의 인라인 자바스크립트가 작동하지 않는다.
  - a 태그에 걸어둔 2개의 이벤트가 모두 작동하였다.
  - 부모 요소인 div 태그에 걸어둔 이벤트는 작동하지 않는다.

2. <div> 클릭시
  - div 태그에 걸어둔 이벤트만 작동한다.

3. <nav> 클릭시
  - 아무런 작동이 없다.

2018년 2월 5일 월요일

최초 접속시 css와 script가 로딩되지 않을때

환경

서버 : 톰캣 단독

문제

스프링을 사용중인 웹 사이트에서 최초 접속시 CSS가 로딩되지 않는 현상이 있었다. 새로고침하면 이후부터는 제대로 나오긴 하지만 브라우저를 닫고 다시 웹 사이트에 접속하면 여전히 처음에는 CSS가 로딩되지 않았다. 그런데 index.html에서 페이지 리다이렉트로 문제의 페이지에 접근한 경우에는 제대로 나왔다. 즉 주소를 직접 입력해서 접속시 최초 1회는 페이지가 제대로 나오지 않는 것이다.

그래서 브라우저의 콘솔을 열어보니 아래와 같은 로그가 꽤 많이 찍혀있었다.
“http://127.0.0.1:9080/gim/;jsessionid=02B695062249B5363476B2D5293A2AF9js/vendor/modernizr-2.8.3-respond-1.4.2.min.js” 소스의 <script> 로딩을 실패하였습니다.

메시지를 보면 script가 로딩되지 않는다고 하는데 script와 더불어 CSS가 함께 로딩되지 않아서 디자인 없이 HTML만 불러오는 상황이었다.

문제가 되는 부분을 jsp 소스에서 찾았고 그 중 일부만 보면 아래와 같은 형식으로 되어있었다.
<link rel="stylesheet" href="<c:url value='/'/>css/main.css">
<script src="<c:url value='/'/>js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>

해결

위의 문제는 <c:url value='/'/>의 결과 값인 /gim의 뒤에 세션아이디가 붙어 "/gim/;jsessionid=19B754062123249B5476B2D5435A2AF3" 처럼 경로가 변하면서 문제가 된 것이었다.

2가지 해결방법을 발견하였는데

첫 번째로 아래처럼 상대 경로로 고쳐서 문제를 해결하였다.

<link rel="stylesheet" href="../css/main.css">
<script src="../js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
이경우 소스보기 시에도 깔끔하게 위와 동일한 소스가 보인다

두 번째로 아래처럼 <c:url>을 고쳐서 문제를 해결하였다.

<link rel="stylesheet" href="<c:url value='/css/main.css'/>">
<script src="<c:url value='/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js'/>"></script>
이 경우 해당 화면에서 소스보기 하면 아래처럼 나타났다.
<link rel="stylesheet" href="/gim/css/main.css;jsessionid=19B754062123249B5476B2D5435A2AF3">
<script src="/gim/js/vendor/modernizr-2.8.3-respond-1.4.2.min.js;jsessionid=19B754062123249B5476B2D5435A2AF3"></script>

<c:url> 사용시 주의하는 것이 좋겠다.



해결을 위해 아래의 블로그가 도움이 되었다.
https://blue_0227.blog.me/130097042737


2018년 1월 25일 목요일

ajax 동기화 처리하기

동기화가 필요한 코드

아래의 코드는 ajax를 통해 로그인 여부 확인 후 로그인이 안된 경우 dwg 확장명을 가진 파일이 다운로드 안되도록 하는 코드이다. 실제 다운로드시 서버 단에서 한번 더 체크하는 부분은 별도로 있다.


수정전

아래처럼 작성한 경우 비동기 처리되어 로그인 여부 확인이 뒤늦게 이루어져서 "다운로드 권한이 없습니다." 라는 메시지가 의도한 대로 잘 작동되지 않는다.



/**
 * 로그온 여부 확인
 * @returns {Boolean}
 */
function isLogon() {
    //데이터 요청
    $.ajax({
        url : contextPath+'/main/isLogon.ajax',
        type : 'POST',
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8',
        success : function(result) {
            //console.log("result : "+JSON.stringify(result));
            //console.log("basicInfoList : "+result.basicInfoList.length);
            return result;
        },
        error : function(request,status,error) {
            console.log("code:"+request.status+"\n\n"+ "message:" + request.responseText + "\n\n"+"error:"+error);
            //alert($(request.responseText.replace(/(\r\n|\n|\r)/gm,"")).text());
            //alert("처리에 실패하였습니다.\ncode:"+request.status+"\n"+"error:"+error);
        },
        complete : function() {
        }
    });
}

$(document).ready(function() {
    /**
     * 파일 다운로드 처리
     */
    $(document).on('click', '.down', function(){
        //로그인 시에만 다운로드 처리
        var ext = ($(this).text().split("."));
        //로그인 여부와 확장자 확인하는 부분
        if (isLogon() == false && ext[ext.length-1].toLowerCase() == "dwg") {
            //로그인이 안되었고 확장자가 dwg라면
            alert("다운로드 권한이 없습니다.");
        } else {
            var fileSn = $(this).data("filesn");
            var seq = $(this).data("seq");
            window.open(contextPath+"/main/filedown.do?seq="+seq+"&fileSn="+fileSn);
        }
    });
});


그래서 $.ajax(); 의 async 속성 사용으로 뭔가 방법을 찾을수 있을까 생각 했지만 async는 deprecated 되었다고 한다. async : false로 설정시 아래의 오류가 발생하였다.

파이어폭스에서... 메인 쓰레드에서의 동기화된 XMLHttpRequest는 사용자 경험에 안좋은 영향을 미치기 때문에 더이상 사용하지 않습니다. 더 자세한 사항은 http://xhr.spec.whatwg.org/ 를 참고해 주십시오.

크롬에서... [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.


수정후

이번엔 조금 다른 병식을 찾아서 적용해 보았다. 이번엔 의도한 대로 작동이 잘 되었다.



/**
 * 로그온 여부 확인
 * @returns {Boolean}
 */
function isLogon() {
    //데이터 요청
    var pormise = $.ajax({
        url : contextPath+'/main/isLogon.ajax',
        type : 'POST',
        //data : JSON.stringify(data),
        //async : false, //deprecated
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8',
        success : function(result) {
            //console.log("result : "+JSON.stringify(result));
            //console.log("basicInfoList : "+result.basicInfoList.length);
        },
        error : function(request,status,error) {
            //console.log("code:" + request.status+"\n\n" + "message:" + request.responseText + "\n\n"+"error:"+error);
            //alert($(request.responseText.replace(/(\r\n|\n|\r)/gm,"")).text());
            //alert("처리에 실패하였습니다.\ncode:"+request.status+"\n"+"error:"+error);
        },
        complete : function() {
        }
    });
 
    return pormise;
}

$(document).ready(function() {
    /**
     * 파일 다운로드 처리
     */
    $(document).on('click', '.down', function(){
        var ext = ($(this).text().split("."));
        var fileSn = $(this).data("filesn");
        var seq = $(this).data("seq");
        var pormise = isLogon();
        var sessionOn = false;

        //jqXHR.done(function( data, textStatus, jqXHR ) {});
        //jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
        //jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
        
        pormise.done(function(result){
            sessionOn = result;
            //console.log(result);
         
            //로그인 여부와 확장자 확인하는 부분
            if (sessionOn == false && ext[ext.length-1].toLowerCase() == "dwg") {
                //로그인이 안되었고 확장자가 dwg라면
                alert("다운로드 권한이 없습니다.");
            } else {
                window.open(contextPath+"/main/filedown.do?seq=" + seq + "&fileSn=" + fileSn);
            }
        });
        //pomise.fail(function(){ ... }); //아직 테스트 못해봄
        //pomise.always(function(){ ... }); //아직 테스트 못해봄
    });
});

2018년 1월 11일 목요일

CSS로 요소에 대한 클릭 등 이벤트 발생 막기

jQuery 이벤트 발생 차단하기


pointer-events: none;

요소에 대한 이벤트 발생을 막고 싶을 때 사용하는 CSS.
이 css가 적용되면 jQuery의 click 등의 이벤트가 동작 되지 않는다.

예제

###############################################
<a class="wid-01" href="#">이벤트</a>

$('.wid-01').css('pointer-events','auto'); //이벤트 가능하도록 처리
$('.wid-01').css('pointer-events','none'); //이벤트 막음
###############################################

2017년 11월 23일 목요일

목록의 체크 선택/해제에 따라 [전체선택] 체크박스를 체크하거나 해제하기

목록의 체크 선택/해제에 따라 [전체선택] 체크박스를 체크하거나 해제하기 


동적으로 생성된 목록에서
체크박스를 모두 선택하면 --> 목록 상단의 [전체선택/해제] 체크박스를 체크하고
체크박스를 하나라도 해제하면 --> 목록 상단의 [전체선택/해제] 체크박스를 체크해제

HTML 부분

아래의 HTML 코드 중 주석 부분을 jQuery로 동적 생성시 제어가 당초 생각했던 코드대로 실행되지 않았다
그래서 동적 생성 HTML일 경우 아래처럼 처리해 보았다
<table id="table-03" class="table table-responsive table-grtc-01 no-margin has-check" summary="사진정보 이력">
    <thead>
    <tr class="text-center-group vertical-middle-group">
        <th>
            <div class="checkbox">
                <input type="checkbox" value="" aria-label="check" title="check" class="cursor-pointer">
                <label></label>
            </div>
        </th>
        <th>촬영일자</th>
        <th>촬영기관</th>
        <th>사진설명</th>
    </tr>
    </thead>
    <tbody>
    <!--
    <tr class="vertical-middle-group">
        <td class="text-center-group">
            <div class="checkbox">
                <input type="checkbox" value="option1" aria-label="check" title="check" class="cursor-pointer">
                <label></label>
            </div>
        </td>
        <td class="text-center">2016/05/16</td>
        <td class="tooltip-demo txt-ellipsis-td">
            <span data-toggle="tooltip" data-placement="top" title="김해시">김해시</span>
        </td>
        <td class="tooltip-demo txt-ellipsis-td">
            <span data-toggle="tooltip" data-placement="top" title="20160415_sample.jpg">20160415_sample.jpg</span>
        </td>
    </tr> -->
    </tbody>
</table>

jQuery 부분

//$('input[name="tpiSeqs"]').click(function(){ //동적 생성된 HTML에서는 작동 안됨
$(document).on('click', 'input[name="tpiSeqs"]', function(){ //동적 생성된 HTML에서도 작동됨
    //var totLength = $(this).length; //이건 항상 1이 나왔음
    var totLength = $('input[name="tpiSeqs"]').length; //이건 예상했던 개수가 나옴
    var chkLength = $('input[name="tpiSeqs"]:checked').length;

    if (totLength > 0 && totLength == chkLength) {
        console.log("on:");
        $('#table-03 thead input:checkbox').prop("checked",true);
    } else {
        console.log("off");
        $('#table-03 thead input:checkbox').prop("checked",false);
    }
});

2017년 11월 22일 수요일

jQuery Ajax를 통해 전송된 데이터를 Controller에서 List 객체로 받기

jQuery Ajax를 통해 전송된 데이터를 Controller에서 List 객체로 받기

아래는 체크박스를 선택하여 jQuery를 통해 대상 항목들을 List 형태로 넘겨받기 위한 처리임 배열로 받아도 되지만 List로 받아야할 상황에서 구현함


html 부분

<div id="facilitiesInfoFileListDiv">
    <div class="checkbox">
        <input id="atchFileIdList0" name="fileSn" value="2" type="checkbox">
        <label for="atchFileIdList0">mou.jpg</label>
    </div>
    <div class="checkbox">
        <input id="atchFileIdList1" name="fileSn" value="3" type="checkbox">
        <label for="atchFileIdList1">korea.png</label>
    </div>
</div>
<div class="overflow-hidden">
    <a href="javascript:void(0)" id="deleteFacilitiesInfoFileBtn" class="btn btn-default btn-delete pull-right">선택삭제</a>
</div>

jQuery 부분

/**
 * 파일 삭제 버튼을 누르면
 */
$('#deleteFacilitiesInfoFileBtn').click(function() {
    //등록할지 물어보기
    if (!confirm('사진을 삭제하시겠습니까?')) {
        return false;
    }

    //매개변수값 정리 : @RequestBody List fileVOList로 담기위한 사전 작업
    var arr = new Array();
    var obj = null;
    $('#facilitiesInfoFileForm input[name="fileSn"]:checked').each(function(i) { //check 된값 배열에 담기
        obj = new Object();
        obj.atchFileId = $('#facilitiesInfoFileForm input[name="atchFileId"]').val();
        obj.fileSn = $(this).val();
        arr.push(obj);
    });
  
    //입력값 전송
    $.ajax({
        url : contextPath+'/mgr/main/deleteFacilitiesInfoFile.ajax',
        type : 'POST',
        data : JSON.stringify(arr),
        dataType : 'json',
        contentType : 'application/json; charset=UTF-8',
        success : function(result) {
            //console.log("result : "+JSON.stringify(result));
            //console.log("message : "+result.message );
            alert(result.message);
        },
        error : function(request,status,error) {
            //console.log("code:"+request.status+"\n\n"+"message:"+request.responseText+"\n\n"+"error:"+error);
            //alert($(request.responseText.replace(/(\r\n|\n|\r)/gm,"")).text());
            alert("처리에 실패하였습니다.\ncode:"+request.status+"\n"+"error:"+error);
        },
        complete : function() {
            selectFacilitiesInfoFileList(); //시설정보 파일목록 새로 불러오기
        }
    });
});

JAVA 부분

/**
 * 이후 컨트롤러에서 해당 리스트를 받을 수 있었다
 */
@RequestMapping("/mgr/main/deleteFacilitiesInfoFile.ajax")
public @ResponseBody Map deleteFacilitiesInfoFile(@RequestBody List fileVOList) throws Exception {
    LOGGER.debug("fileVO.getFileVOList().size():"+fileVOList.size());
    fileMngService.deleteFileInfs(fileVOList);

    Map result = new HashMap();
    result.put("message", egovMessageSource.getMessage("success.common.delete"));
    return result;
}

2017년 11월 8일 수요일

동적으로 추가된 html 엘리먼트 jQuery로 제어하기

동적으로 추가된 html element 제어하기

일반적인 경우 아래처럼 선택자를 사용한다
$('#table-03 tbody td:eq(1)').click(function() {});

그러나
$('#table-03 tbody').html("<tr><td><i class=\"fa fa-pencil cursor-pointer\"></i></td></tr>");
위 코드처럼 엘리먼트가 추가된 경우

아래처럼 선택자를 바꿔서 사용해야 했다.
$(document).on('click', '#table-03 tbody td:eq(1)', function(){});

jQuery radio 제어하기

jQuery radio 제어하기

라디오 선택하기

$('#conditionSetting input:radio[name="tcpScopeCode"][value="PST001002"]').prop('checked', true);

라디오 체크 안된 것 disabled 처리

$('#conditionSetting input:radio[name="tcpScopeCode"]:not(:checked)').prop("disabled",true);

라디오 전체 선택 해제하기

$('input:checkbox[name="aaa"]').prop("checked",false);

2017년 8월 9일 수요일

모든 링크를 읽어들여 기존의 태그 뒤에 새창열기 태그를 추가하기 예

모든 링크를 읽어들여 기존의 태그 뒤에 새창열기 태그를 추가하기 예

index.html

<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>프레임</title>
</head>
<frameset cols="250, *" frameborder="no" border="0" framespacing="0">
<frame name="left" scrolling="no" src="./left.html">
<frame name="main" scrolling="auto" src="">
</frameset>
</html>

left.html

<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>메뉴</title>
<script type="text/javascript" src="js/lib/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
$("body").find("a").each(function() {
if ($(this).prop("target") == "main") {
$(this).parent().append($('<a />', {
href: $(this).prop("href"),
target: '_blank',
title: '새창보기',
text: '[새창]',
style: 'padding-left: 5px; font-size: 8pt;'
}));
}
});
});
//-->
</script>
</head>
<body>
<div>
<dl>
<dt><a href="//localhost/Cesium-1.35" target="main">Cesium-1.35</a></dt>
<dt><a href="//localhost/msac" target="main">msac</a></dt>
<dt><a href="left_sub.html">left_sub</a></dt>
</dl>
</div>
</body>
</html>

2017년 6월 20일 화요일

jQuery로 접속 주소(URL) 알아내기

# jQuery 소스
console.log("url1 : "+$(location).attr('href'));
console.log("protocol : "+$(location).attr('protocol'));
console.log("host : "+$(location).attr('host'));
console.log("pathname : "+$(location).attr('pathname'));
console.log("search : "+$(location).attr('search'));

# 출력결과
url1 : http://localhost:8080/msac/main.do?ddd=ddd
protocol : http:
host : localhost:8080
pathname : /msac/main.do
search : ?ddd=ddd

2017년 5월 17일 수요일

jquery 사용자정의 속성의 사용

jquery 사용자정의 속성의 사용

1. 아래와 같이 태그에 속성을 지정한 후
(속성명은 반드시 소문자만 사용해야 함)
<p data-programcd="111"></p>


2. 아래처럼 jquery로 호출하면 값을 불러올 수 있음
$(this).data("programcd"));

3. 그런데 동적 HTML 생성 등의 복잡한 처리를 하는 과정에서 경우에 따라 data()가 잘 인식되지 않을때가 있었다. 이런경우 attr()을 써서 해결할 수 있었다.
$(this).attr('data-programcd')