【问题标题】:Ajax request is not calling Spring boot controllerAjax 请求未调用 Spring Boot 控制器
【发布时间】:2018-11-24 11:16:05
【问题描述】:

我正在尝试使用 Ajax 调用我的 Spring 控制器并提交一个表单。

函数总是检索错误窗口。我尝试将 URL 参数更改为 "/profile""profile""PrivateAreaController/profile",但我一直收到相同的错误.

我的main.js文件和控制器按以下顺序放置:

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

我的控制器叫PrivateAreaController

Ajax 代码

$('#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;
    }); 

弹簧代码

@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 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>

编辑:

我找到了答案..我需要添加

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

@RequesMapping参数前,将ajax调用的url参数改为url:'http://localhost:8080/(yourrequestmapping参数)

【问题讨论】:

  • 错误是什么? data 的内容看起来不像是有效的 JSON。

标签: java ajax spring spring-mvc spring-boot


【解决方案1】:

我找到了答案..我需要添加

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

在@RequesMapping参数之前,将ajax调用的url参数改为url:'http://localhost:8080/(yourrequestmapping参数)

【讨论】:

    【解决方案2】:

    这对我使用带有百里香的sp​​ringboot很有用,对这篇文章How do you get the contextPath from JavaScript, the right way?的答案之一进行了小修改

    在 HTML 中

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

    然后在 JS 中

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        嗯。我以前从未见过这部分。

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

        我通常喜欢如下:

         $.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");
                }
         });
        

        但它可能与 contextPath 有问题。 所以,我要做的是添加 'request.getContextPath()/' 如下:

             $.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");
                }
            });
        

        contextPath 包含您的起始页的 URL。 例如,“www.google.com”或“www.naver.com”

        但总的来说,由于我个人经常使用contextPath,所以我做了一个值并保留它。

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

        然后,您的代码将看起来整洁且易于重用。

        你也可以用error属性来解决。

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

        我希望这会成功。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-03
          • 1970-01-01
          • 2016-05-17
          • 2021-06-12
          • 2016-01-27
          • 1970-01-01
          • 1970-01-01
          • 2021-05-31
          相关资源
          最近更新 更多