index.html
<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:"./hello",
type:"post",
datatype:"json",
data:{id:$("#id").val(), pwd:"123"},
success:function(json){
//alert("success");
//alert(json);
//alert(json[0].id);//zxc
//alert(json[0].name);//홍길동
//alert(json[0].address);//대전시
//화면 html에 올리기 -> for or each
$.each(json, function(i, val) {
$("#demo").append("i: " + i + " id: "+ val.id
+ " name: " + val.name
+ " address: " + val.address + "<br>")
});
},
error:function(){
alert("error");
}
});
});
});
</script>
</body>
HelloServlet.java
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
* String str = "hello";
*
* String gson = new Gson().toJson(str); resp.getWriter().write(gson);
*/
List<CustUserDto> list = new ArrayList<CustUserDto>();
list.add(new CustUserDto("zxc", "홍길동", "대전시"));
list.add(new CustUserDto("fgh", "향단이", "여수시"));
//json으로 변환
resp.setContentType("application/json");
//한글을 줄력
resp.setCharacterEncoding("utf-8");
//gson-2.8.5.jar 추가 후
String gson = new Gson().toJson(list);
//return해주는 함수
resp.getWriter().write(gson);
}
}
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접근 //list//map//obj (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 |