본문 바로가기

Ajax

MVC model1 // .html <- .jsp 접근

첫화면

 

 

 

 

 

 

index.html

<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="demo"></p>
<br>
<button type="button">click</button>

<script type="text/javascript">
$(function() {
	$("button").click(function() {
		
		$.ajax({
			url:"data.jsp",
			type:"get",
			datatype:"json",
			success:function( obj ){
				//alert("success");
				//alert(obj);//{"num":1001, "number":"1001" }
				
                
                //json받아옴
				let json = JSON.parse(obj);//String -> JSON으로 변경
				//alert(json);
				alert(json.name);//홍길동
				alert(json.num);//1001
			},
			error: function() {
				alert("error");
			}
		});
	});
});
</script>
</body>

 

 

 

 

data.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%

/////////MVC model1
//DB접근
String userName = "홍길동";
int userNumber = 1001;

//문자열로 넘어옴
String json = "{\"num\":" + userNumber + ", \"name\":\"" + userName + "\" }";
System.out.println(json);

//외부로 보냄
	out.println(json);//{"num":1001, "number":"1001" }
%>