您的位置:首页 > 理论基础 > 计算机网络

jQuery ajax提交请求,springmvc控制层接收参数示例以及HTTP请求中Content-Type介绍

2017-08-24 16:24 627 查看
通过jQuery发送http请求到springmvc控制层,以及控制层接收参数示例:

if ($('#instanceTbodyDiv', parent.document).find(':checkbox:checked').length != 1) {
$.alert({
icon: 'fa fa-warning',
content: '请选择1条记录进行操作'
});
return false;
}

var trs = [];
$('#pagingTbodyDiv').find(':checkbox:checked').each(function() {
trs.push($(this).parents('tr'));
});
var tr = trs[0];
var id = tr.find('td:eq(1)').text();
var name = tr.find('td:eq(4)').text();

/*单独传参,contentType需要设置成 application/x-www-form-urlencoded
默认地,表单数据会以这种contentType提交。 */
$.ajax({
url: '/workerManage/fixLeader',
contentType: 'application/x-www-form-urlencoded',
type: 'post',
async: false,
data: {
id: id,
name: name
},
success: function (result) {
/*
@RequestMapping(value="fixLeader", method = {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public JSONResult fixLeader(@RequestParam(value="id", required = true) String id, @RequestParam(value="name", required = true) String name) {
上面@RequestParam()这些可以不要。
也可以直接通过url拼接传递参数?id=1&name=haha
如果controller方法包含参数HttpServletRequest req,那么也可以通过 logger.info(req.getParameter("id") + req.getParameter("name"));获取到传递的值
*/
}
});

/*json传参,注意contentType需要设置成 application/json
@RequestBody让我们可以直接以application/json请求并在到达controller层获得已反序列化的对象*/
var vo = {id: id, name: name};
$.ajax({
url: '/workerManage/update',
contentType: "application/json",
type: "POST",
data: JSON.stringify(vo),
timeout: 0,
success: function (result) {
/*
@RequestMapping(value = "/update", method = {RequestMethod.POST})
@ResponseBody
public JSONResult update(@RequestBody WorkerEntity workerEntity) {
*/
}
});

/*path传参*/
$.ajax({
url: 'workerManage/start/' + id,
contentType: 'application/json',
type: "POST",
success: function (result) {
/*
@RequestMapping(value="start/{id}", method=RequestMethod.POST)
@ResponseBody
public JSONResult start(@PathVariable("id")int id) {
*/
}
});

/*传递数组*/
var ids = [];ids.push(1);ids.push(2);
$.ajax({
url: 'workerManage/delete',
contentType: 'application/json',
type: "POST",
data: JSON.stringify(ids),
success: function (result) {
/*
@RequestMapping(value = "/delete", produces = "application/json")
@ResponseBody
public JSONResult delete(@RequestBody int[] ids) {
*/
}
});

/*url传参*/
$.ajax({
url: "/workerManage/get?id=100",
contentType: "application/json",
type: "GET",
timeout: 0,
success: function (result) {
/*
@RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json")
@ResponseBody
public WorkerEntity get(int id) {
*/
}
});

/*传一个json对象,然后通过path传其它值*/
var vo = {notice: "haha"};
$.ajax({
url: "/chou/transferPathVal3/zhouzhichao/26",
contentType: "application/json",
type: "POST",
data: JSON.stringify(vo),
success: function (result) {
/*
@RequestMapping(value = "/transferPathVal3/{name}/{age}")
@ResponseBody
public JSONResult transferPathVal3(@RequestBody Notice notice, @PathVariable String name, @PathVariable int age) {
*/
}
});

/*传一个json对象,然后通过URL传其它值*/
var vo = {workerName: "alarmWorker", workerType: 2};
$.ajax({
url: "/workerManage/add?name=cc&age=18",
contentType: "application/json",
type: "POST",
data: JSON.stringify(vo),
timeout: 0,
success: function (result) {
/*
@RequestMapping(value = "/add", method = {RequestMethod.POST})
@ResponseBody
public JSONResult add(@RequestBody WorkerEntity workerEntity,String name,int age) {
*/
}
});

 "application/json; charset=utf-8"  和  "application/x-www-form-urlencoded"的区别:

 "application/json; charset=utf-8"是告诉服务端你是在post json格式的数据,像这样:{ Name : 'John Smith', Age: 23}

"application/x-www-form-urlencoded" 是告诉服务端你是把参数编码放到URL中或者请求体中,像这样:Name=JohnSmith&Age=23

 "application/json; charset=utf-8"  和  "application/x-www-form-urlencoded"都是告诉服务器客户端发送的请求的编码格式。

HTTP 协议是以 ASCII 码传输,建立在 TCP/IP 协议之上的应用层规范。HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。实际上,开发者完全可以自己决定消息主体的格式,只要最后发送的 HTTP 请求满足上面的格式就可以。

但是,数据发送出去,还要服务端解析成功才有意义。

服务端通常是根据请求头(headers)中的 Content-Type 字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到 POST 提交数据方案,包含了 Content-Type 和消息主体编码方式两部分。

常用的编码方式有:

1.application/x-www-form-urlencoded  最常见的 POST 提交数据的方式。原生 form 表单默认以这种方式提交数据

2.multipart/form-data  一般用来上传文件

3.application/json  用来告诉服务端消息主体是序列化后的 JSON 字符串

4.text/xml   XML作为编码方式

HTTP POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8。

jquery在执行post请求时,会默认设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。

curl发送http请求

curl -X POST 'http://localhost:8080/formPost' -d 'id=1&name=foo&mobile=13612345678'

curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/jsonPost' -d '{"id":2,"name":"foo","mobile":"13656635451"}'

curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/mixPost?sex=1' -d '{"id":2,"name":"foo","mobile":"13656635451"}'

参考:http://blog.csdn.net/mhmyqn/article/details/25561535
https://stackoverflow.com/questions/9870523/differences-in-application-json-and-application-x-www-form-urlencoded http://blog.csdn.net/mhmyqn/article/details/25561535 http://blog.csdn.net/tycoon1988/article/details/40080691
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax jquery spring mvc