jquery ajax 用 data 和 headers 向 java RESTful 傳遞參數區別


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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM