我有,如果你使用的是創建一個簡單包裝的取()有許多改進純粹的JSON REST API:
// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data), // send it as stringified json
credentials: api.credentials, // to keep the session on the request
headers: Object.assign({}, api.headers, headers) // extend the headers
}).then(res => res.ok ? res.json() : Promise.reject(res));
};
// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
'csrf-token': window.csrf || '', // only if globally set, otherwise ignored
'Accept': 'application/json', // receive json
'Content-Type': 'application/json' // send json
};
// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
api[method] = api.bind(null, method);
});
要使用它,你有變量api
和4的方法:
api.get('/todo').then(all => { /* ... */ });
而一個async
函數內:
const all = await api.get('/todo');
// ...
實施例與jQuery:
$('.like').on('click', async e => {
const id = 123; // Get it however it is better suited
await api.put(`/like/${id}`, { like: true });
// Whatever:
$(e.target).addClass('active dislike').removeClass('like');
});
您使用的是什麼瀏覽器? –
@KrzysztofSafjanowski chrome 42,這意味着[完全獲取支持](http://caniuse.com/#search=fetch) – Razor
檢查此小提琴https://jsfiddle.net/abbpbah4/2/什麼數據你'重新期待?因爲https://fiddle.jshell.net/echo/json的請求顯示空對象。 '{}' –