如何使用Jquery向POST mvc应用程序发送POST请求

时间:2016-02-29 09:46:59

标签: java jquery spring spring-mvc

我创建了一个这样的控制器。

@Controller
public class LoginController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello() {
        return "hello world";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public User login(@RequestBody final User user) {
        return user;
    }

}

当我用bash发送请求时:

 curl -H "Content-Type: application/json" -d '{"username":"xyz"}' http://localhost:8080/mvc/login.do {"id":null,"name":null,"password":null}%

效果很好。

但是当我发出这样的请求时,我收到了错误POST http://localhost:8080/mvc/login.do 415 (Unsupported Media Type)

$.ajax({  method: "POST",
        data: JSON.stringify("{
            'id': 'test,
            'name': 'test1'
        }"),
        url:"login.do",
        timeout: 60000,
        success: sign_submited,
        error: ajaxError
    });

1 个答案:

答案 0 :(得分:3)

尝试将ajax请求中的内容类型设置为 - contentType:"application/json; charset=utf-8",