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>
<input type="text" id="id">
<button type="button">click</button>
<script type="text/javascript">
$(function() {
$("button").click(function() {
$.ajax({
url:"custuser",
type:"get",
datatype:"json",
//data:"id=abc&pwd=123",
//data:{id:"abc", pwd:"123"},
data:{id:$("#id").val(), pwd:"123"},//입력받은 값 가져와 servlet으로 넘겨주기
success:function(json){
//alert("success");
//1
//Servelt에서 넘어오는 str(단순 문자열)
//alert(json.str);//Hello
//2
//map 접근하기
//alert(json.map.title);//사과
//3
//list 받기
let custlist = json.map.custlist;
//alert(custlist); //[object Object],[object Object]
alert(custlist[0].id);
alert(custlist[0].name);
},
error:function(){
alert("error");
}
});
});
});
</script>
</body>
CustUserServlet.jave
@WebServlet("/custuser")
public class CustUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("CustUserServlet doGet");
String id = req.getParameter("id");
String pwd = req.getParameter("pwd");
System.out.println("id: " + id+" pwd: " + pwd);
JSONObject jobj = new JSONObject();
/* 1
* //Client로 전송 할 data를 Map으로 잡음
*
* HashMap<String, Object> map = new HashMap<String, Object>();
*
* //key값 생성
* map.put("title", "사과");
*
* //단순 문자열을 json Object로 날리기
* //jobj.put("str", "Hello");
*
* //map을 json Object으로 변경하여 날리기
* jobj.put("map", map);
*
* //한글 깨지지않게 설정
* resp.setContentType("application/x-json; charset=UTF-8");
*
* //데이터를 통째로 보내줌
* resp.getWriter().print(jobj);
*/
//list에 data를 저장
List<CustUserDto> list = new ArrayList<CustUserDto>();
list.add(new CustUserDto("aaa", "홍길동", "서울시"));
list.add(new CustUserDto("bbb", "일지매", "부산시"));
//HashMap에 list를 저장
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("custlist", list);
//전송할 데이터를 추가
jobj.put("map", map);
resp.setContentType("application/x-json; charset=UTF-8");
resp.getWriter().print(jobj);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("CustUserServlet doPost");
}
}
CustUserDto.java
public class CustUserDto implements Serializable {
private String id;
private String name;
private String address;
'Ajax' 카테고리의 다른 글
MVC model2// 회원관리 (0) | 2020.07.24 |
---|---|
MVC model2 // .html <- servlet .java접근 // gson// 화면에 뿌리기 (0) | 2020.07.24 |
MVC model1 // .html <- .jsp 접근 (0) | 2020.07.24 |
Html에서 $.ajax로 xml 파씽 (0) | 2020.07.24 |
Html 에서 $.ajax로 .json 호출 (0) | 2020.07.24 |