Content-Type 實體頭部用於指示資源的 MIME 類型 media type 。
語法
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=something
參數 | 說明 |
---|---|
media-type | 資源或數據的 MIME type |
charset | 字符編碼標准 |
boundary | boundary |
常見 media-type
- text/plain
- application/json
- application/x-www-form-urlencoded
- multipart/form-data
幾種請求設置 Content-Type 的方式
XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://xxx.xxx.com/xxx', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send('a=1&b=2');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://xxx.xxx.com/xxx', true);
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.send(JSON.stringify({ a: 1, b: 1 }));
JQuery.ajax
$.ajax({
type: 'post',
url: 'https://xxx.xxx.com/xxx',
contentType: 'application/x-www-form-urlencoded',
data: { a: 1, b: 1 }, // ajax 會自動轉成 a=1&b=2
success: function () { },
})
$.ajax({
type: 'post',
url: 'https://xxx.xxx.com/xxx',
contentType: 'application/json',
data: JSON.stringify({ a: 1, b: 1 }),
success: function () { },
})
JQuery.ajax 本質是封裝 XMLHttpRequest , contentType 即 content-type , 默認 application/x-www-form-urlencoded 。
注意
- data 如果不是 string , 會使用 jQuery.param 轉換成 = & 拼接的 search 格式,然后用 xml.send 方法發送。
- dataType 預期服務器返回的數據類型。會通過下面對象轉換后插入 accept。
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
Fetch
fetch('https://xxx.xxx.com/xxx', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'a=1&b=2',
})
fetch('https://xxx.xxx.com/xxx', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ a: 1, b: 1 }),
})
三種數據傳輸方式
Query String Parameters
從問號 (?) 開始的 URL(查詢部分)。

Form Data
application/x-www-form-urlencoded

Request Payload
application/json
