您的位置:首页 > Web前端 > JQuery

jquery ajax 用 data 和 headers 向 java RESTful 传递参数区别

2016-12-26 19:20 561 查看
jquery 的 ajax 是非常方便的一个函数,记录一下 $.ajax 生成的 http 报文

一、使用 data 传递参数:

1 $.ajax({
2      url : "webrs/test/addBook",
3      type : "POST",
4      data:{
5          id : "xx",
6          name : "中",
7          price : "xx"
8      },
9
10      contentType: "text/plain; charset=utf-8"
11 });


此时生成的 http 报文类似于下面这样:

POST /WS_BookStore/faces/webrs/test/addBook HTTP/1.1 (CRLF)
Host: localhost:8080 (CRLF)
Connection: keep-alive (CRLF)
Content-Length: 22 (CRLF)
Pragma: no-cache (CRLF)
Cache-Control: no-cache (CRLF)
Accept: */* (CRLF)
Origin: http://localhost:8080 (CRLF)
X-Requested-With: XMLHttpRequest (CRLF)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 (CRLF)
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 (CRLF)
Referer: http://localhost:8080/WS_BookStore/faces/deleteBook.html (CRLF)
Accept-Encoding: gzip, deflate, br (CRLF)
Accept-Language: zh-CN,zh;q=0.8 (CRLF)
Cookie: JSESSIONID=ab94dd581643b1b96e0190c3bbeb (CRLF)
(CRLF)         //该CRLF表示消息报头已经结束,在此之前为消息报头
id=xx&name=%E4%B8%AD&price=xx


参数在 http 的正文部分,在 RESTful 中使用注解 @FormParam 可以获取到此参数

1 @POST
2     @Produces("application/json; charset=UTF-8")
3     @Path("addBook")
4     public String addBook(@FormParam("id") int BookID,  @FormParam("name") String BookName,  @FormParam("price") int Price) {
5         // ...
6     }


二、使用 headers 传递参数

1 $.ajax({
2      url : "webrs/test/addBook",
3      type : "POST",
4      headers:{
5          id : "xx",
6          name : "xx",
7          price : "xx"
8      },
9
10      contentType: "text/plan; charset=utf-8"
11 });


此时生成的 http 报文类似于下面这样:

POST /WS_BookStore/faces/webrs/test/addBook HTTP/1.1 (CRLF)
Host: localhost:8080 (CRLF)
Connection: keep-alive (CRLF)
Content-Length: 0 (CRLF)
Pragma: no-cache (CRLF)
Cache-Control: no-cache (CRLF)
Origin: http://localhost:8080 (CRLF)
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
id: xx (CRLF) // 注意参数 id 在这里
Content-Type: text/plan; charset=utf-8 (CRLF)
Accept: */* (CRLF)
X-Requested-With: XMLHttpRequest (CRLF)
name: xx (CRLF) // 注意参数 name 在这里
price: xx (CRLF) // 注意参数 price 在这里
Referer: http://localhost:8080/WS_BookStore/faces/deleteBook.html (CRLF)
Accept-Encoding: gzip, deflate, br (CRLF)
Accept-Language: zh-CN,zh;q=0.8 (CRLF)
Cookie: JSESSIONID=ab94dd581643b1b96e0190c3bbeb (CRLF)


参数在 http 的报头部分,在 RESTful 中使用注解 @HeaderParam 可以获取到此参数

1 @POST
2 @Produces("application/json; charset=UTF-8")
3 @Path("deleteBook")
4 public String deleteBook(@HeaderParam("id") int BookID) {
5     // ...
6 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: