1. 程式人生 > >測試jquery中ajax的post提交與springController接收的一些疑問

測試jquery中ajax的post提交與springController接收的一些疑問

[email protected] String型別可接收 ajax中data為物件的資料,並以key=value(utf-8編碼)展現:

  • ajax提交:
    data:{aa:"你好 中國 中國"},
    contentType:"application/json"

  • controller接收:
    接收方式
    接收結果
    如果stringify處理過data, map的值就是正常的json串

  • 兩點需要注意:

    1.jquery的ajax會把object物件string化
    2.contentType=”application/json”,未指定編碼格式,data的中文編碼均utf-8格式編碼,contetnType如下設定編碼格式均無效,
    //contentType:”application/json”,
    contentType:”application/json; charset=gbk”,
    //contentType:”application/json;charset=utf-8”
    並且頁面設定了meta依然無效:meta charset=”gbk”

2.data不是json格式時,@RequestBody String body,接收,介面返回400錯誤(aa沒有加雙引號,使用了stringify,不加引號也可正常傳送)

  • 使用json.stringify()

    //data:{aa:”你好 中國 中國5”}改為下面的方式:
    data:JSON.stringify({aa:”你好 中國 中國5”}),

    否則報錯:Status Code: 400 Bad Request

    使用實體接收也是400
    @RequestBody ReceiveModel model

3. 使用JSON.stringify處理data,但不設定contentType=application/json時(預設 application/x-www-form-urlencoded; charset=utf-8)

  • 此時 @requestbody String body 的值會有些特別
    bb=bb&%7B%22aa%22%3A%22%E4%BD%A0%E5%A5%BD++%E4%B8%AD%E5%9B%BD++%E4%B8%AD%E5%9B%BD5%22%7D=
    解碼後:bb=bb&{“aa”:”你好 中國 中國5”}=,即body的值作為一個key傳入了

  • 此時 @requestbody Entity entity 則報415錯誤:415 Unsupported Media Type

  • 因此應該呆以認為:x-www-form-urlencoded:charset=utf-8傳上來的body都是string型別

4. ajax不使用json.stringify處理data, 後臺用@requestbody Entity entity 接收(預設的contentType:x-www-form-urlencoded)

data:{"aa":"你好  中國  中國"},
@RequestBody ReceiveModel model

報錯:415 Unsupported Media Type

使用 @requestbody  String body依然報錯:
報錯:415 Unsupported Media Type

- 不使用json.stringity, 無論是entity還是string都無法接收body

5. List與陣列均可以接收 data中的陣列屬性

實體屬性:
private List<String> names;

private String[] names2;

ajax data:
data:JSON.stringify({aa:"你好  中國  中國5","names":    ["a","b","c"],"names2":["a","b","c"]}),