我目前正在迁移 ajax
的使用到fetch
,但是我需要 Ajax native 的参数/函数 beforeSend: function()
。我想执行相同的操作,而不需要在 fetch 中实现(例如创建一个新类)
jQuery $.ajax
结构:
$.ajax({
url: '...',
type: 'post',
data: {...},
beforeSend: function() {
// perform the action..
},
success: function(response, status, xhr) {
// receive response data
}
});
JavaScript fetch
结构:
fetch('...').then((response) => {
return response.text();
}).then((data) => {
console.log(data);
});
如何在不需要实现或在获取时创建新类的情况下确定这样的函数。有什么办法或者只有实现吗?由于我的搜索,我只找到了类似 CustomFetch
的实现( Is there a beforesend Javascript promise ) 和其他。
最佳答案
问题已解决!
无需实现和/或创建新的fetch
类。仅使用参数作为“函数内的函数”。我希望你能帮助别人!
function ipGetAddress(format) {
requestFetch = function() {
// perform the action..
console.log('** beforeSend request fetch **');
return fetch.apply(this, arguments);
}
requestFetch(`https://api.ipify.org?format=${format}`).then((response) => {
return response.json();
}).then((data) => {
console.log(data.ip);
});
}
ipGetAddress('json') // return local ip address..
关于javascript - 发送前 : function() in fetch API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66080100/