Cooper's devlog

6-1. AJAX를 활용한 답변 추가 1 본문

Programming/Spring-boot

6-1. AJAX를 활용한 답변 추가 1

cooper_dev 2020. 8. 3. 00:12

1. 강의 링크

https://www.youtube.com/watch?v=hK3RWBAKX3I&list=PLqaSEyuwXkSppQAjwjXZgKkjWbFoUdNXC&index=48

 


2. 학습 목표

AJAX를 활용해 답변을 추가하는 기능 구현(1)

 

 


3. 과정

사용자가 답변하기 기능을 구현했을 때, 서버에서 데이터가 바로 전송되지 않도록 기능 구현

- 그러기 위해서는 클릭하는 시점을 잡아야 한다.(jquery를 이용한 구현법)

 

 

1. form class 이름 변경

show.html

 

2. script.js 내용 작성

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
$(".answer-write input[type=submit]").click(addAnswer);
 
function addAnswer(e){
    console.log("click me"); //java : System.out.println고 같은 역할
    e.preventDefault(); // server가 데이터 전송이 원할하지 않게하기 위한 작업.
    
    var queryString = $(".answer-write").serialize(); //서버로 전달할 테이터를 읽어 오기.
    console.log("query : " + queryString);
    
    var url = $(".answer-write").attr("action");
    console.log("url : " + url);
    
    
    $.ajax({
            type :  'post',
            url : url,
            data : queryString,
            dataType : 'json',
            error : onError,
            success : onSuccess
            });
}
 
//실패 시, 호출 method
function onError(){
}
 
//성공 시, 호출 method
function onSuccess(data, status){
    console.log(data);
}
 

e : 클릭이 발생되는 이벤트 정보가 오게 되어 있음

정확한 출력 확인 방법  : 개발자 도구 > console에 값이 전달되는지를 확인하기

 

 

클릭 시, console 화면

 

3. AnswerController 내용 변경

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
40
package net.slipp.web;
 
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import net.slipp.domain.Answer;
import net.slipp.domain.AnswerRepository;
import net.slipp.domain.Question;
import net.slipp.domain.QuestionRepository;
import net.slipp.domain.User;
 
@RestController
@RequestMapping("/api/questions/{questionId}/answers")
public class AnswerController {
    
    @Autowired
    private QuestionRepository questionRepository; 
    
    @Autowired
    private AnswerRepository answerRepository; 
    
    @PostMapping("")
    public Answer create(@PathVariable Long questionId, String contents, HttpSession session) {
        if(!HttpSessionUtils.isLoginUser(session)) {
            return null;
        }
        
        User loginUser = HttpSessionUtils.getUserFromSession(session);
        Question question = questionRepository.findById(questionId).get();
        Answer answer = new Answer(loginUser, question ,contents);
 
        return answerRepository.save(answer);
    }
}
 
 

 

@RequestMapping 내용 변경

1./question/{questionId}/answers → /api/question/{questionId}/answers

  • /api/-- : 응답을 json형태 혹은 data형태로 전달하겠다는 의미.

 

2. @Contorller   @RestController

  • @ResfulController : 데이터 타입을 json으로 전환하는 annotation

 

3. 결과 확인

-data 내용에 formatteredCreateDate 내용만 출력되는 이유 : 객체에서 getter/setter 선언한 변수만 호출되는

것으로 판단

console 결과


 

 

Comments