HTTP Headers Content-Type 詳解


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


免責聲明!

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



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