Http 請求響應與內容協商(二)-$Ajax 和 Spring mvc
一、jquery $.ajax 中的引數說明
1、contentType:傳送資料到伺服器時所使用的內容型別。簡單的說就是告訴服務我從的是什麼型別。
預設是:"application/x-www-form-urlencoded"。
2、dataType:預期的伺服器響應的資料型別。
3、data: 規定要傳送到伺服器的資料。
以使用者資訊為例:
3.1、物件:{"userId":'1232',"userName":"222"}
3.2、字串:
3.2.1、表單資料:"userId=1&userName=222"
3.2.2、JSON字串:'{"userId":'1232',"userName":"222"}'
也可以json.stringify({"userId":'1232',"userName":"222"})轉成json字串
二、Spring mvc 請收引數
1、當content-type:指定的是application/json時,接收引數指定@RequestBody
messageConvert會從request.getInputStream()取出資料轉型成JSON物件。
當傳的資料不是json字串時
丟擲org.springframework.http.converter.HttpMessageNotReadableException
: JSON parse error。
2、當content-type:application/x-www-form-urlencoded時,指定了@RequestBody,
丟擲throw new HttpMediaTypeNotSupportedException這個異常。
3、當content-type:application/x-www-form-urlencoded時,可以用JavaBean接收,
也可以@RequestParam("userId")接收。
特別注意當用JavaBean接收時,如果引數型別不對應將丟擲錯誤。
public class User { private long userId; private String userName;
}
丟擲:org.springframework.validation.BindException:
org.springframework.validation.BeanPropertyBindingResult
Failed to convert property value of type 'java.lang.String' to required type 'long' for property 'userId';
nested exception is java.lang.NumberFormatException: For input string: "12.32"]
三、前端後端一致,資料正常接收
1、ajax 不指定content-type就是預設(application/x-www-form-urlencoded),
data 傳送JSON 物件,結果正常接收。
前端:
後端:
瀏覽器:上面明確是表單資料
2、ajax 不指定content-type就是預設(application/x-www-form-urlencoded),
data 傳送表單字串,結果正常接收。
前端:
後端:
瀏覽器:
3、ajax 指定content-type:"application/json",data 指定
json字串,後端使用@RequestBody接收,結果正常接收。
前端:
後端:
瀏覽器:
四、前端後端不致,導致資料不能正常接收
1、前端不指定content-type就是預設(application/x-www-form-urlencoded),
後端使用@RequestBody
前端:
後端:
2、前端指定content-type:"application/json",data:為JSON物件,
後端使用@RequestBody
前端:
後端:
3、前端不指定content-type就是預設(application/x-www-form-urlencoded),
資料型別不正確。
前端:
後端: