首页 > 解决方案 > beforeSend: fetch API 中的 function()

问题描述

我目前正在将使用迁移ajaxfetch,但是我需要 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);
});

如何在不需要实现或在获取时创建新类的情况下确定这样的功能。有没有办法或只有实施?由于我的搜索,我只找到了CustomFetchIs there a beforesend Javascript promise)等实现。

标签: javascriptfetch

解决方案


解决了问题!

无需实现和/或创建新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..


推荐阅读