简体   繁体   中英

Ajax request is not calling Spring boot controller

I'm trying to call my Spring controller using Ajax and submitting a form.

Function always retrieves the error window. I tried changing the URL parameter to "/profile" , "profile" or "PrivateAreaController/profile" , but I keep getting the same error.

My main.js file and controller are placed in the following order:

-->Mainfolder
    -->src
       -->java
          -->controller
              -->PrivateAreaController.java
       -->resources
           -->static
              -->js
                 -->main.js

My controller is called PrivateAreaController

Ajax Code

$('#sampleForm').submit(
    function(event) {
        var firstname = $('#firstname').val();
        var lastname = $('#lastname').val();
        var data = 'firstname='
            + encodeURIComponent(firstname)
            + '&lastname='
            + encodeURIComponent(lastname);
        $.ajax({
            type : "POST",
            dataType: "json",
            url : '@Url.Action("callingcontroller","PrivateAreaController")',
            contentType: "application/json; charset=utf-8",
            data : data,
            success : function(response) {
                alert( response );
            },
            error : function() {
                alert("not working");
            }
        });
        return false;
    }); 

Spring code

@RequestMapping(value = "/profile", method = RequestMethod.POST)
        public @ResponseBody
        String processAJAXRequest(
                @RequestParam("firstname") String firstname,
                @RequestParam("lastname") String lastname   ) {
            String response = "";

            System.out.println("working");
            return response;
        }

HTML form

<form id="sampleForm" method="post" action="/profile">
         <input type="text" name="firstname" id="firstname"/>
         <input type="text" name="lastname" id="lastname"/>
         <button type="submit" name="submit">Submit</button>
</form>

EDIT:

I found the answer.. i needed to add

@CrossOrigin(origins = "http://localhost:8080")

before the @RequesMapping parameter and change the url parameter of the ajax call to url: ' http://localhost:8080/(your requestmapping parameter)

I found the answer.. i needed to add

@CrossOrigin(origins = " http://localhost:8080 ")

before the @RequesMapping parameter and change the url parameter of the ajax call to url: ' http://localhost:8080/(your requestmapping parameter)

This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?

In the HTML

        <html>
            <head>
                <link id="contextPathHolder" th:data-contextPath="@{/}"/>
            <body>
                <script src="main.js" type="text/javascript"></script>
            </body>
        </html>

THEN IN JS

  var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
  $.get(CONTEXT_PATH + 'action_url', function() {});

您遇到什么错误,按 F12 并转到“网络”选项卡,然后按“提交”按钮现在可以看到 url,尝试添加 url:"../your service URL..

Well. I never seen this part before.

@Url.Action("callingcontroller","PrivateAreaController")

I normally do like as below:

 $.ajax({
        type : "POST",
        dataType: "json",
        url : '/profile',
        contentType: "application/json; charset=utf-8",
        data : data,
        success : function(response) {
            alert( response );
        },
        error : function() {
            alert("not working");
        }
 });

But it can have a problem with the contextPath. So, What I do is adding 'request.getContextPath()/' as below:

     $.ajax({
        type : "POST",
        dataType: "json",
        url : '${request.getContextPath()}/profile',
        contentType: "application/json; charset=utf-8",
        data : data,
        success : function(response) {
            alert( response );
        },
        error : function() {
            alert("not working");
        }
    });

The contextPath has the URL of your start page. For instance, 'www.google.com' or 'www.naver.com'

But in general, Since I personally use the contextPath a lot, I make a value and keep it.

var context = ${request.getContextPath()};

Then, your code will look neat and easy to reuse.

And also you can figure it out with the error attribute.

        error : function(err) {
            console.log("not working. ERROR: "+JSON.stringify(err));
        }

I hope this works out.

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