javascript - beforeSend: fetch API 中的 function()
问题描述
我目前正在将使用迁移ajax
到fetch
,但是我需要 Ajax 本机的参数/函数beforeSend: function()
。我想执行相同的操作而不需要在 fetch 中实现(例如创建一个新类)
jQuery$.ajax
结构:
$.ajax({
url: '...',
type: 'post',
data: {...},
beforeSend: function() {
// perform the action..
},
success: function(response, status, xhr) {
// receive response data
}
});
JavaScriptfetch
结构:
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..
推荐阅读
- reactjs - 如何使用样式组件设置所有元素的样式?
- android - 为什么android toast消息总是在我的应用程序中显示appname:message?
- ssl - 仅来自某些服务器的链中自签名证书
- python-3.x - 在解析文件时制作一行列表
- haskell - 如何遍历字符列表并在 Haskell 中操作字符?
- python - 如何使用 opencv 从市场传单中获取产品图片?
- c++ - 使用 & 的基于范围的 for 循环
- spring-boot - 为什么 Spring Boot @Value 将属性值读取为 1 而不是 001?
- angular - (点击)在 ionic 3 上更新后更改了吗?
- bash - 大于比较在 Bash 中给出不一致的结果