不知道为什么AJAX表单数据向MVC控制器发送null

时间:2017-08-03 03:45:58

标签: javascript jquery ajax spring

我使用AJAX发送表单数据,我的Spring MVC控制器获得null值,但如果我使用 Postman ,它将正常工作。

这是我的ajax电话:

$.ajax({
    type: "post",
    url:"http://localhost:8080/fivenet/mobile/api/login",
    crossDomain: true,
    data: JSON.stringify(formData),
    dataType: 'json',
    contentType: 'text/html;charset=UTF-8',
    //contentType: 'application/json;charset=utf-8',
    beforeSend: function(xhr){
    },
    success: function(msg){
        console.log('sucess');
    },
 error: function(msg){}

这是我的控制器:

@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "create-account", method = RequestMethod.POST)
public @ResponseBody RespondMessage createAccount(
        @RequestParam(value = "data", required = true) String dataString,
        HttpServletRequest request) throws Exception {

    RespondMessage responsed = new RespondMessage();
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    JSONObject data = new JSONObject(dataString);
 return responsed;
}

2 个答案:

答案 0 :(得分:0)

试试这段代码:

var formData = {"username" : "username", "password" : "password"};

$.ajax({
    type: "POST",
    url: "http://localhost:8080/fivenet/mobile/api/login",
    data: JSON.stringify(formData),
    dataType: 'json',
    contentType: 'application/json;charset=utf-8',
    beforeSend: function(xhr){
    },
    success: function(data){
        alert(data)
    },
    failure: function(errMsg) {
        alert(errMsg);
    },
    error: function(errMsg){
         alert(errMsg);
    }

答案 1 :(得分:0)

我终于解决了这个问题。它是我提供数据的方式。

out

感谢所有人的关注