简体   繁体   中英

how to call java controller method from jsp using ajax

i have implemented different solution of this problem but i am unable to access the controller method from jsp some solution that i have used are following

<script type="text/javascript">
var entryId = arguments[0]; 
function callMetod()
    {
   <%!public void clickBtn() {
    ControllerJSP controller = new ControllerJSP();
    controller.likePicture();
    }%>

    }
    </script>

solution 2 is

<script type="text/javascript">
var entryId = arguments[0]; 
function callMetod()
{
    var entryId = arguments[0]
    $.post( "../controllerJSP/LikePicture", {eid: 232 })
    .done(function( data ) {
    alert( "Data Loaded: " + data );
 });
 </script>

Solution three that i can implemented is

 <script type="text/javascript">
 function callMetod()
 {
      `
         var f={};
                var response = "4292";              
                f.url = "../controllerJSP/LikePicture";
                f.type = "POST";
                f.dataType = "json";
                f.data={eId:entryId};
                f.contentType = "application/json";
                f.success = function (entryId) {
                    console.log(json)

                    alert("success");
                };

                f.error = function (){
                    alert("failed");
                };

                $.ajax(f);
                alert("run")
 }
 </script>

please help me to resolve this issue

i will find a solution to call the method inside jsp from controller put an annotation requestmapping and assign a name as shown below and call this annotation in your ajax url like shown below

     @RequestMapping("likePicture")
     @ResponseBody
     public void likePicture(@RequestParam("eId") String eId, Map<String, Object>map)
     {
          List<LikeCount> likeCounts = new ArrayList<>();
          likeCounts = dal.getLikeCount(eId);
          SimpleResponseModel srm = new SimpleResponseModel();
          srm = dal.likePicture(eId, "n@n.com");
          dal.updateLikeCount(srm.getMessage(), eId);
          System.out.println(srm.getMessage());
      }

ajax method is shown here

    function likeImg(id, votes) 
    {
        var btn = document.getElementById("likeBtn");
        debugger
        $.ajax({

            url : "../likePicture",
            type : "GET",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data : {eId:id, vote:votes},
            success : function(responce) {
                alert("ok")
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM