简体   繁体   English

AJAX 正在使用 POST 映射将所有 null 数据发送到 Spring Controller?

[英]AJAX is sending all null data to the Spring Controller using POST mapping?

I am trying to send data from HTML Form with POST mapping using ajax to the spring controller. But it's sending all null data.我正在尝试使用 ajax 将数据从 HTML 表单发送到 spring controller。但它正在发送所有 null 数据。 Tried lots of variation for ajax. It's sending the school object but all fields are null. The console shows the fields are saving but all becomes null in the AJAX.为 ajax 尝试了很多变化。它正在发送学校 object,但所有字段都是 null。控制台显示字段正在保存,但在 AJAX 中全部变为 null。

Here is the createSchoolForm.html这是 createSchoolForm.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Create School || EDUBD</title>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
</head>
<body>
    <h1>EDUBD - Manage School Portal</h1>

    <h3>Create New School</h3> <br>

    <form id="createSchool">
        <br>
        <label>School Name:
        <input type="text" id="schoolName"  value="" />
        </label>
        <br>
        <label>School Email:
        <input type="text" id="schoolEmail" value="" />
        </label>
        <br>
        <label>School Phone Number:
        <input type="tel" id="schoolPhone" value="" />
        </label>
        <br>
        <input id="btn" type="submit" value="Submit" />
    </form>

    <div id="feedback"></div>



    <script>
        $(document).ready( function() {
            $("#createSchool").submit(function(e){
                e.preventDefault();
                var schoolData = {
                    schoolName: $("#schoolName").val(),
                    schoolEmail: $("#schoolEmail").val(),
                    schoolPhone: $("#schoolPhone").val(),
                    status: null,
                    schoolStreet: null,
                    schoolHouse: null,
                    schoolZip: null,
                    schoolCity: null,
                    schoolState: null,
                    schoolCountry: null,
                    image: null,
                    createBy: null,
                    updatedBy: null,
                    createdDate: null,
                    updatedDate: null,
                    id: null
                };
               // let j = JSON.stringify(schoolData);
                console.log(JSON.stringify(schoolData));

                $.ajax({
                    header:{
                        contentType : 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    type : "post",
                    url : "Create",
                    data : JSON.stringify(schoolData),
                    dataType : "json",
                    success: function (data) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + JSON.stringify(data, null, 4) + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("SUCCESS : ", data);
                    },
                    error: function (e) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + e.responseText + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("ERROR : ", e);
                    }
                });
            });
        });

    </script>

</body>
</html>

Here is the controller:这是 controller:

    @ApiOperation(value = "Create School")
    //@PostMapping(BASE_SCHOOL_PATH+"/Create")
    @PostMapping(value = BASE_SCHOOL_PATH+"/Create", produces = {"application/json"},
            consumes = {"application/x-www-form-urlencoded"})
    public  String create (School school, @ApiIgnore HttpServletResponse response) throws IOException {
        // components tests are expecting this assertion and exception handling, and will fail if removed
        try {
            Assert.isNull(school.getId(), "School ID field must be null");
            Assert.notNull(school.getSchoolEmail(),"School email cannot be null.");
            Assert.notNull(school.getSchoolPhone(),"School Phone number cannot be null. ");
            Assert.isNull(schoolDao.readByEmail(school.getSchoolEmail()),"School already exists in the system.");
            schoolDao.create(school, null);
            return "createSchoolForm";
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return null;
        }
    }

Inside your ajax function, Try sending the data as form data:在您的 ajax function 中,尝试将数据作为表单数据发送:

First, create a form data object by using the HTML Form:首先,使用HTML Form创建一个表单数据object:

let createSchoolForm = document.getElementById('createSchool');
let formData = new FormData(createSchoolForm );

Then, add it to the data key in the Ajax object. Remove the header and dataType as it may conflict with the Ajax communication.然后将其添加到Ajax object中的data键中。去除headerdataType ,因为它可能与Ajax通信冲突。

 $.ajax({
                    type : "post",
                    url : "Create",
                    data : formData
                    success: function (data) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + JSON.stringify(data, null, 4) + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("SUCCESS : ", data);
                    },
                    error: function (e) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + e.responseText + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("ERROR : ", e);
                    }
                });

Full Example:完整示例:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>Create School || EDUBD</title>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
</head>
<body>
    <h1>EDUBD - Manage School Portal</h1>

    <h3>Create New School</h3> <br>

    <form id="createSchool">
        <br>
        <label>School Name:
        <input type="text" id="schoolName"  value="" />
        </label>
        <br>
        <label>School Email:
        <input type="text" id="schoolEmail" value="" />
        </label>
        <br>
        <label>School Phone Number:
        <input type="tel" id="schoolPhone" value="" />
        </label>
        <br>
        <input id="btn" type="submit" value="Submit" />
    </form>

    <div id="feedback"></div>



    <script>
        $(document).ready( function() {
            $("#createSchool").submit(function(e){
                e.preventDefault();
                var schoolData = {
                    schoolName: $("#schoolName").val(),
                    schoolEmail: $("#schoolEmail").val(),
                    schoolPhone: $("#schoolPhone").val(),
                    status: null,
                    schoolStreet: null,
                    schoolHouse: null,
                    schoolZip: null,
                    schoolCity: null,
                    schoolState: null,
                    schoolCountry: null,
                    image: null,
                    createBy: null,
                    updatedBy: null,
                    createdDate: null,
                    updatedDate: null,
                    id: null
                };
               // let j = JSON.stringify(schoolData);
                console.log(JSON.stringify(schoolData));

               let createSchoolForm = document.getElementById('createSchool');
               let formData = new FormData(createSchoolForm );

                $.ajax({
                    type : "post",
                    url : "Create",
                    data : formData 
                    success: function (data) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + JSON.stringify(data, null, 4) + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("SUCCESS : ", data);
                    },
                    error: function (e) {
                        var json = "<h4>Ajax Response</h4>&lt;pre&gt;"
                            + e.responseText + "&lt;/pre&gt;";
                        $('#feedback').html(json);
                        console.log("ERROR : ", e);
                    }
                });
            });
        });

    </script>

</body>
</html>

The Solution that worked for me.对我有用的解决方案。

I have tried different ways to solve the problem.我尝试了不同的方法来解决这个问题。 It actually helped me to understand how HTTP request works.它实际上帮助我理解了 HTTP 请求是如何工作的。 Here is the solution that worked for me.这是对我有用的解决方案。 I used XMLHttpRequest() to send the data from the HTML form.我使用 XMLHttpRequest() 从 HTML 表单发送数据。 After sending, I had to capture the data with @RequestBody .发送后,我必须使用@RequestBody捕获数据。 This is important for the POST to work.这对于 POST 的工作很重要。 I also had 2 different produces and consumes in my controller. Had to match those.我的 controller 中也有 2 种不同的producesconsumes 。必须匹配它们。 Lastly, used <button> in place of <input> for the submission.最后,使用<button>代替<input>进行提交。

The Solution解决方案

New HTML looks like this:新的 HTML 看起来像这样:

 <h3>Create New School</h3> <br>
    <form id="createSchool" method="post">
        <br>
        <label>School Name:
        <input type="text" id="schoolName"  value="" required/>
        </label>
        <br>
        <label>School Email:
        <input type="email" id="schoolEmail" value="" required/>
        </label>
        <br>
        <label>School Phone Number:
        <input type="tel" id="schoolPhone" value="" required/>
        </label>
        <br>
        <button type="button" id="submit">Submit Form</button>
    </form>

    <div id="feedback"></div>

    <script>
        $(document).ready( function() {
            $("#submit").click(function(e) {
                e.preventDefault();
                var school=new Object(); //creating object to add values. 
                school.schoolName = $("#schoolName").val();
                school.schoolEmail= $("#schoolEmail").val();
                school.schoolPhone = $("#schoolPhone").val();
                school.status= null;
                school.schoolStreet= null;
                school.schoolHouse= null;
                school.schoolZip= null;
                school.schoolCity= null;
                school.schoolState= null;
                school.schoolCountry= null;
                school.image= null;
                school.createBy= null;
                school.updatedBy= null;
                school.createdDate= null;
                school.updatedDate= null;
                school.id= null;

                var s2=JSON.stringify(school);
                console.log(s2);

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "SchoolCreate",true);
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.onreadystatechange = function() { // Call a function when the state changes.
                    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
                        // Request finished. Do processing here.
                        console.log("success");
                        $('#feedback').html("Success");
                    }
                    else {
                        console.log(xhr.responseText);
                        $('#feedback').html(xhr.responseText);
                    }
                }
                xhr.send(s2);

                //This will empty the fields after submission.
                document.getElementById('schoolName').value='';
                document.getElementById('schoolEmail').value='';
                document.getElementById('schoolPhone').value='';


            });
        });
    </script>

</body>

The Controller: Controller:

    @ApiOperation(value = "Create School")
    @PostMapping(value = "/ManageSchool"+BASE_SCHOOL_PATH+"/SchoolCreate", produces = {"application/json"},
            consumes = {"application/json"})
    public String create (@RequestBody School school, @ApiIgnore HttpServletResponse response) throws IOException {
        // components tests are expecting this assertion and exception handling, and will fail if removed
        try {
            Assert.isNull(school.getId(), "School ID field must be null");
            Assert.notNull(school.getSchoolEmail(),"School email cannot be null.");
            Assert.notNull(school.getSchoolPhone(),"School Phone number cannot be null. ");
            Assert.isNull(schoolDao.readByEmail(school.getSchoolEmail()),"School already exists in the system.");
            schoolDao.create(school, null);
            return "createSchoolForm";
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return null;
        }
    }

These answers helped me to find some ground in the end.这些答案最终帮助我找到了一些基础。

How to transfer data from HTML to controller Spring 如何将数据从HTML转移到controller Spring

XMLHttpRequest not sending POST data XMLHttpRequest 不发送 POST 数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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