[node js] ajax 초 간단 예제
view-
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<input type="text" id="msg" />
<input type="button" id="ajax_test" value="ajax_test" />
<!--이곳에 결과 값이 붙는다.-->
<div id="result"></div>
<!--ajax 작동 로직-->
<script>
$('#ajax_test').click( function() {
$('#result').html('');
$.ajax({
url: '/board/ajax', //주소
dataType: 'json', //데이터 형식
type: 'POST', //전송 타입
data: {'msg':$('#msg').val()}, //데이터를 json 형식, 객체형식으로 전송
success: function(result) { //성공했을 때 함수 인자 값으로 결과 값 나옴
if ( result['result'] == true ) {
$('#result').html(result['msg']);
}
} //function끝
}); // ------ ajax 끝-----------------
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
server 부분
/*ajax 테스트 로직*/
router.get('/getajax', function(req, res, next) {
res.render("main/ajax");
});
/* POST 호출 처리 */
router.post('/ajax', function(req, res, next) {
console.log('POST 방식으로 서버 호출됨');
//view에 있는 data 에서 던진 값을 받아서
var msg = req.body.msg;
msg = '[에코]' + msg;
//json 형식으로 보내 준다.
res.send({result:true, msg:msg});
});