首页 > 解决方案 > Ajax 请求未调用 Spring Boot 控制器

问题描述

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

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

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

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

我的控制器被称为PrivateAreaController

阿贾克斯代码

$('#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/(你的requestmapping参数)

标签: javaajaxspringspring-mvcspring-boot

解决方案


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

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

在 @RequesMapping 参数之前并将 ajax 调用的 url 参数更改为 url:' http://localhost:8080/(你的requestmapping 参数)


推荐阅读