简体   繁体   中英

Spring MVC, jQuery with ajax - getting 415

I am using Jquery to send an AJAX POST request. On success I need to redirect the user to a different page, on failure I want to stay on the page with the same data.

I am having 2 issues.

  1. On SUCCESS, it is not redirecting, it stays on same URL & gives a 415
  2. On FAILURE, I get a 415 instead of the page getting rendered.

Here is my code:

 var jsonResponse = [];
 //jsonResponse is being constructed from the form data, on submit.

 var req = {
            "name" : "${name}",
            "id" : "${id}",
            "data" : jsonResponse
    };


 $.ajax({
        url: "url",
        type: "POST",
        dataType: 'json',
        contentType:'application/json',
        async: false,
        data: JSON.stringify(req),
        success: function(result) {

            url = window.location.href;
            url = url.replace("processData", "getData");
            alert(url); //prints localhost:8000/getData
            location.href = url; //stays on localhost:8000/processData
        },
        error: function() {
            alert("--- Failure ---");
            // should stay on same page with the previous data, but
            //returns a 415.
        }
    });

Controller for url1

 @RequestMapping(value = "processData", method = RequestMethod.POST)
public String post( Model model,
                    HttpServletRequest httpServletRequest, 
                    @RequestBody FormModel model) {

}

Controller for url2:

@RequestMapping(value = "getData", method = RequestMethod.GET)
public String get(Model model, HttpServletRequest httpServletRequest)
{
}

I am attaching snapshot of the Error Message I get. 在此输入图像描述

What am I doing wrong here?

The issue was with the form. I had a Submit button which was also submitting the data after AJAX call ended. So I had to remove that functionality.

Initially:

<input type="Submit" value="Submit" />

Now:

<input type="button" value="Submit" />

Better approach is to override the default Submit functionality.

 $('form').on('submit', function(e) {
    e.preventDefault();

Here the answer to a question I asked : Form Processing via AJAX - Avoiding both GET & POST Requests from getting generated

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