Content-Type是一個請求頭參數,決定了發送的數據格式是以怎樣一種編碼方式傳送的。ajax
get請求是沒有Content-Type請求頭的。數據是按鍵值對的形式拼接在url後面傳送到後端。Post請求的請求頭Content-Type是經過在form表單添加屬性enctype來肯定的,能夠設置兩種值application/x-www-form-urlencoded以及 multipart/form-data.json
view source: 後端
get請求是沒有Content-Type請求頭的。數據是按鍵值對的形式拼接在url後面傳送到後端。Post請求的請求頭經常使用的有application/x-www-form-urlencoded、multipart/form-data、appliction/json.bash
function Request(type, url, data, header){
var xhr = new XMLHttpRequest(); //不考慮IE兼容
var type = type.toUpperCase();
if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
data = str.replace(/&$/, '');
}
xhr.open(type, url, true);
if(header) {
Object.keys(header).forEach((key) => {
xhr.setRequestHeader(key, header[key]);
})
}
xhr.send(data);
}
Request('POST', 'www.xxx.com', {firstname: 'mickey', lastname: 'Mouse' }, {"Content-Type": "application/x-www-form-urlencoded"})
複製代碼
function mapToFormData(obj) {
const formData= new FormData()
Object.keys(obj).forEach(attr => {
formData.append(attr, obj[attr])
});
return formData;
}
var data = {
firstname: 'mickey',
lastname: 'Mouse'
}
var formatData = mapToFormData(data)
var xhr = new XMLHttpRequest();
xhr.open('POST', 'xxx.com', true);
xhr.send(formatData)
複製代碼
var data = {
firstname: 'mickey',
lastname: 'Mouse'
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'xxx.com', true);
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(data))
複製代碼