简体   繁体   中英

Jquery Ajax POST not working. works fine for GET

I am trying to post jquery Ajax request but it does not go to my MVC controller.

$.ajax({
            url : contextPath + "/check/panelnumber",
            type : "POST",
            contentType : "application/json",               
            data :{
                    "execution" : execution,
                    "panelNumber" : panelNumber
            },
});

Spring MVC controller

@Controller
@RequestMapping("/check")
public class ValidateFieldValueController extends FlowEnabledBaseController {

@RequestMapping(value = "/panelnumber", method = RequestMethod.POST)
public ResponseEntity<String> checkPanelNumber(HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("panelNumber") String panelNumber,
        @RequestParam("execution") String execution) {
......
Gson gson = new Gson();
return new ResponseEntity<String>(gson.toJson(details), HttpStatus.OK);
}

However it works perfectly fine for GET method! Tried adding dataType: "json" as well but with this even GET call stops working. Browser console shows error as HTTP 400 bad request but when checked through firefox plugins the POST parameters are going fine. Any help?

Spring is a little touchy when it comes to @RequestParam, POST body, and JSON content-type: it simply won't parse them. You can solve this problem one of three ways:

  1. Change the content-type to be application/x-www-form-urlencoded
  2. Change the two @RequestParam to be a single @RequestBody Map<String, Object> body , then use that Map to manually parse out your parameters.
  3. Set up a custom Argument Resolver that can parse JSON for your desired values.

The second method is likely the easiest to change, but it loses you some of the automagic validation that Spring does for you.

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