2012-01-03 2 views
1

이 기능을 클릭하면 버튼이 클릭됩니다.jquery ajax with spring mvc3 사용 방법

그냥 데이터베이스에 삽입하십시오.

삽입 행은

문제는 항상 '오류 경고'를 반환한다 ... 완벽하지만.

'성공 알림'은 반환되지 않습니다.

하는 방법.

ps. 나는 나의 영어에 유감 스럽다 좋지 않다.

$(function(){ 
    $("[name='replyWrite']").click(function(){ 
     var text = $("textarea").val(); 
     $.ajax({ 
      url: "http://localhost:8080/replyWrite", 
      type: "POST", 
      data: "no=100&id=test&comment=this is test", 
      dataType: "text", 
      cache: "false", 
      success: function(){ 
       alert("Success"); 
       // something to do 
      }, 
      error: function(data, textStatus, errorThrown){ 
       alert("error\n" + data + ", " + textStatus + ", " + errorThrown); 
      } 
     }); 
    }); 
}); 

그리고 replyWrite 코드입니다 ..

@RequestMapping(value="/replyWrite") 
public String replyWrite(@RequestParam(required=true)int no 
         , @RequestParam(required=true)String id 
         , @RequestParam(required=true)String comment){ 
    return boardDaoJdbc.replyWrite(id, no, comment); 
} 



public String replyWrite(String id, int no, String comment){ 
    // it will be return "1" 
    return Integer.toString(this.jdbcTemplate.update("INSERT INTO testz_board_reply(id, comment, linked_idx, write_date) VALUES (?, ?, ?, DATE_FORMAT(now(), '%Y-%c-%d %H:%i')) ", 
          id, comment, no)); 
} 

답변

2

당신이 @ResponseBody 주석을 사용하는 당신이 필요로 아약스를 사용하는 경우.

그래서 당신의 매핑은 다음과 같이해야합니다 : 내 클라이언트 측에서 이제

@RequestMapping(value="/replyWrite", method=RequestMethod.POST) 
@ResponseBody 
public String replyWrite(@RequestParam(required=true)int no 
         , @RequestParam(required=true)String id 
         , @RequestParam(required=true)String comment){ 
    return boardDaoJdbc.replyWrite(id, no, comment); 
} 

:

<script src="../scripts/jquery-latest.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 

    $("#replyWrite").click(function() { 
     var text = $("textarea").val(); 
     var request = "no=100&id=test&comment=this is test", 
     $.post("replyWrite", request, 
        function(data) { 
        alert(data); 
        }); 
     }); 
     }); 
</script> 

는 도움이되기를 바랍니다.

+0

정말 고마워요 !!! – lng0415

0

문제는 당신의 URL과 함께 아마도 : http://localhost:8080/replyWrite. 어떤 컨텍스트 경로 아래에 WAR 애플리케이션을 배치했다면 URL에서이 컨텍스트 경로를 사용해야합니다.

예를 들어 - Tomcat의 ROOT 폴더 안에 webapps 폴더가 있습니다.이 "webapp"에만 컨텍스트 경로가 비어 있습니다. WAR이 example.war 인 경우 URL은 http://localhost:8080/example/replyWrite이어야합니다.

이 문제를 해결하는 일반적인 방법은 자바 스크립트에 약간의 서버 측 처리를 추가하여 URL을 생성하는 것입니다 (하드 코딩하는 대신). JSP를 사용하여 예를 들어

:

$.ajax({ 
    url: "<c:url value="/replyWrite" />", 
    ... 

관련 그르 Grzybek

+0

AJAX 자바 스크립트를 별도의 js 파일에 넣을 때 무엇을 할 수 있습니까? 이게 효과가 있니? – saarthak