[jQuery]教學-jQuery.ajax() contentType和dataType的差別

每次都忘記特別記錄一下,jQuery.ajax()參數的contentTypedataType的區別如下。

contentType

contentType是網頁要送到Server的資料型態,若沒指定則預設為'application/x-www-form-urlencoded; charset=UTF-8'

dataType

dataType是網頁預期從Server接收的資料型態,若沒指定則jQuery會根據response的MIME type來推定為xmljsonscripthtmltext

 

如果從頁面要透過jQuery.ajax()以post傳json資料至後端,並預期接收回json資料的設定如下。

var data = {"name":"matt"}
$.ajax({
  url : '../getUser'
  type : 'post', 
  dataType : 'json', // 預期從server接收的資料型態
  contentType : 'application/json; charset=utf-8', // 要送到server的資料型態
  data : JSON.stringify(data),
  success : function(result) {
    console.log(result.success); // result是json物件
  },
});

Springf MVC Controller的設定如下

@RequestMapping(value = "/getUser", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String getUser(@RequestBody Map<String, Object> obj){ 
  ... 
  JSONObject jsonObj = new JSONObject()
  return jsonObj.toString();
}

 

如果從頁面要透過jQuery.ajax()以post傳表單資料至後端,並預期接收回json資料的設定如下。

$.ajax({
  url : '../getUser'
  type : 'post',
  dataType : 'json',
  contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
  data : $('#myForm').serialize(),
  success : function(result) {
    alert(result.success); // result是json物件
  },
});

Springf MVC Controller的設定如下

@RequestMapping(value = "/getUser", method=RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String getUser(@RequestBody User user){ 
  ... 
  JSONObject jsonObj = new JSONObject()
  return jsonObj.toString();
}

 

如果從頁面要透過jQuery.ajax()以post直接傳JavaScript物件至後端,並預期接收回json資料的設定如下。

var data = {"name":"matt"}
$.ajax({
  url : '../getUser'
  type : 'post',
  dataType : 'json',
  contentType : 'application/x-www-form-urlencoded; charset=UTF-8', // 不能用 'application/json; charset=utf-8'
  data : data, // 不用JSON.stringify()
  success : function(result) {
    alert(result.success); // result是json物件
  },
});

如果覺得文章有幫助的話還幫忙點個Google廣告,感恩。

  • Top