WEB관련
AJAX POST방식(JSON 사용)
JUMP개발자
2020. 4. 7. 00:17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// post 방식 (시도 숙제 ) JSON 방식
function idchkbtn3(){
fid = document.getElementById('tid');
fpassword = document.getElementById('tpassword');
console.log(fid.value);
console.log(fpassword.value);
var data = {
"id" : fid.value,
"pw" : fpassword.value
}
ajax.onreadystatechange = callbackajax;
console.log(JSON.stringify(data));
// post 방식
ajax.setRequestHeader("Content-Type", "application/json");
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
위와 같이 객체를 생성하고 , Content-Type을 applicaiton/json으로 설정한다.
JSON.stringfy는 객체를 JSON 문자열로 전환하는 메서드.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
@RequestMapping("/rest_idchk_post")
public int rest_idchk_post(HttpServletRequest request, @RequestBody Map<String, Object> data) {
ModelAndView mav = new ModelAndView();
HashMap<String, Object> map = new HashMap<String, Object>();
System.out.println("data" + data);
if(StringUtils.isEmpty(id)) {
mav.addObject("msg", "id 또는 비밀번호를 입력하시기 바랍니다.");
return 0;
}
map.put("id", id);
map.put("password", password);
int count =0;
try {
count= infodao.loginAction(map);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("count " + count);
if(count > 0) {
return 1;
} else {
return 0;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
서버단에서는 위와 같이 @RequestBody를 이용하여 JSON을 받는 형태로 사용하면 된다.
POST방식은 Header가 아닌 Body부분에 데이터를 실어서 보내기 때문에 request.getParameter를 이용하여 데이터를 받을 수가 없다.