fetch可以更加簡單的獲取數據,可以看作Ajax的升級版,是基於Promise實現的
1、使用語法
<script>
fetch('http://localhost:3000/fdata').then(function(data) {
return data.text(); // 通過調用text返回promise對象
}).then(function(data) {
console.log(data); // 得到真正的結果
})
</script>
2、fetch請求參數
method(String): http請求方法,默認為GET(GET、POST、PUT、DELETE)
body(String): http的請求參數
headers(Object): http的請求頭,默認為{}
(1)get請求方式的參數傳遞 (傳統方式)
fetch('http://localhost:3000/books?id=123', {
method: 'get'
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
get請求方式的參數傳遞 (Restful方式)
fetch('http://localhost:3000/books/123', {
method: 'get'
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
(2)delete請求方式的參數傳遞
fetch('http://localhost:3000/books/789', {
method: 'delete'
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
(3)post請求方式的參數傳遞 (字符串類型參數)
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
post請求方式的參數傳遞 (json對象類型參數)
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: 'kun',
pwd: '321'
}),
headers: {
'Content-Type': 'application/json'
}
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
(4)put請求方式的參數傳遞(字符串類型參數)
fetch('http://localhost:3000/books/768', {
method: 'put',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
put請求方式的參數傳遞(json對象類型參數)
fetch('http://localhost:3000/books/768', {
method: 'put',
body: JSON.stringify({
uname: 'kun',
pwd: '321'
}),
headers: {
'Content-Type': 'application/json'
}
}).then(function(data) {
return data.text();
}).then(function(data) {
console.log(data);
})
3、fetch響應結果
fetch('http://localhost:3000/json')
.then(function(data) {
return data.json(); // 返回json對象形式
}).then(function(data) {
console.log(data);
})
fetch('http://localhost:3000/json')
.then(function(data) {
return data.text(); // 返回字符串類型
}).then(function(data) {
console.log(data);
})
