티스토리 뷰
let positionList;
let dutyList;
$.ajax({
url : contextPath + "/empInfoManage/getPositionDuty",
type : "post",
dataType : "json",
data : {
compSeq: compSeq
},
success : function(response) {
$(response.data).each( (index, item) => {
if( item.positionSeq.charAt(0) == 'G'){
positionList = response.data.slice(0, index - 1);
dutyList = response.data.slice(index);
return false;
}
});
},
error : function(xhr, status, e) {
console.error(status + ":" + e);
}
})
console.log(positionList);
console.log(dutyList);
위 코드를 실행하면 positionList, dutyList 둘다 undefined가 나온다
ajax는 비동기이기때문에 끝날때까지 기다린다음 값을 받아서 다음으로 가는게아닌 요청만 해두고 바로 다음으로 넘어가기때문에 찍히는값이 undefined다
그래서 아래의 코드를 수행해야한다
let positionList;
let dutyList;
$.ajax({
url : contextPath + "/empInfoManage/getPositionDuty",
type : "post",
dataType : "json",
data : {
compSeq: compSeq
},
success : function(response) {
$(response.data).each( (index, item) => {
if( item.positionSeq.charAt(0) == 'G'){
positionList = response.data.slice(0, index - 1);
dutyList = response.data.slice(index);
return false;
}
});
return 0;
},
error : function(xhr, status, e) {
console.error(status + ":" + e);
}
}).then( () => {
positionList.forEach( val => {
($(".position").append("<option value='" + val.positionSeq + "'>" + val.positionName + "</option>"));
});
dutyList.forEach( val => {
console.log(val);
$(".duty").append("<option value='" + val.positionSeq + "'>" + val.positionName + "</option>");
});
});
ajax에서 0이라는 값을 리턴해주었기때문에 then을 이용하여 그 값을 확인할수있다 then에서 작업할때는 positionList, dutyList에 값이 들어간상태이므로
작업할수있다
위 코드에서 val.positionSeq, val.positionName이 서로 같은이유는 DB에서 UNION을 사용하여 값을 가져왔기때문이다 오타아님
'JavaScript > JQuery' 카테고리의 다른 글
[JQuery & DataTable] DataTable을 사용하기위해 필요한 파일들 (0) | 2019.06.13 |
---|---|
[JQuery] DataTable이 다 그려진후 작업을 해야할때 (0) | 2019.06.13 |
[JQuery & UI] JQuery UI dialog 예,아니요 값 전달 (0) | 2019.06.13 |
[JQuery & UI] JQuery UI 플러그인을 이용한 dialog (0) | 2019.06.13 |
[JQuery & DataTable] hidden column 만들기 (0) | 2019.06.12 |