简体   繁体   中英

Spring & jQuery: AJAX call can't find path to Controller function

Ok so I'm submitting a simple form to my Spring Controller through jQuery. Here is the code:

<form id="addNote" role="form" action="addNote" method="POST">
        <div class="form-group error">
            <label for="note">Enter your Note </label>
            <textarea rows="3" cols="50" name="note" class="form-control"
                id="note"></textarea>
        </div>
        <div class="alert alert-danger" style="display: none">
            <strong>Error!</strong> Text length must not exceed 100 characters
        </div>
        <button type="submit" class="btn btn-default">Save Note</button>

$(document).ready(function(){
    $("#addNote").submit(function(e){
        e.preventDefault();
        var formObj = $(this);
        var formURL = "addNote";
        var formData = $("#note").val();
        $.ajax({
            url: formURL,
            type: 'POST',
            data: formData,
            success: function(response){
                alert(response);
            },
            error: function(response){

            }
        });
    });
});

And the Controller method:

@RequestMapping(value="/addNote", method=RequestMethod.POST)
public Vector<String> addNote(Locale locale, Model model, HttpServletRequest httpServletRequest, HttpSession httpSession){
    String note = httpServletRequest.getParameter("note");
    notes.add(note);
    ModelAndView mv = new ModelAndView("notes");
    mv.addObject("thenotes", notes);
    return notes;
}

I need to return the notes object to the jQuery so that I can display it's data as output. But this is the error I'm getting in the Chrome console:

在此处输入图片说明

So apparently there is a problem in the path. I have tried changing var formURL = "addNote"; to var formURL = "assessment/addNote"; in the jQuery but it doesn't work.

But for some reason if I change return value of addNote() function in the Controller to ModelAndView and return mv then it works but it's not the response in the jQuery I need.

First of all You are using AJAX, so You can't return data using modelAndView.You have to return data as xml/json.

In Your javascript code add the following function:

function getContextPath() {
       return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
    }

reference: How do you get the contextPath from JavaScript, the right way?

Then change You formURL to:

var formURL = getContextPath()+"/addNote";

With the above code requests reaches the controller. Within the controller You have to change Your requestMapping a bit:If You want to return some simple message then You can return it as a string(I am not sure whether it is the best way, but this is how I do it)

@RequestMapping(value = "/addNote", produces=MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
        @ResponseBody
        public String showNote(){

            System.out.println("saving note..");

             return "<response>Example</response>";

        }

If You want to return a Vector or java object to JQuery, then the best idea is to use jackson-mapper or some similar library, You can find info easily with google.A simpler(not necessarily better solution) would be to define a method that would create the xml String by looping through the vector, sth like:

<notes>
<note>note1</note>
<note>note2</note>
</notes>

and return it as a String from controller, and then process xml within JQuery.

I also learn spring, so if someone knows a better solution, I will be happy to read it ;-)

Regards, Mikajlo8

EDIT:I Have changed the requestMethod to GET, otherwise You have to deal with CSRF TOKENS.If You want to use POST, is is easy to find on the internet how to deal with csrf tokens.

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