【问题标题】:jquery ajaxComplete equivalent in axiosjquery ajaxComplete 在 axios 中的等价物
【发布时间】:2021-01-07 22:35:05
【问题描述】:

开始学习 axios,我很喜欢它!

快速的问题,找不到答案,也许没有。

在jQuery ajax 中有一个叫ajaxComplete 的方法,我在徘徊,如果在axios 中有一个等价物?

【问题讨论】:

    标签: javascript jquery ajax axios


    【解决方案1】:

    axios 使用承诺。你可以使用

    axios.get(url,[options]).then(res=>{
    /* hande it here */
    })
    

    如果您没有基础知识,请查看 js promise 的工作原理https://web.dev/promises/

    对于全局处理 axios 事件,这可能会有所帮助 https://auralinna.blog/post/2019/global-http-request-and-response-handling-with-the-axios-interceptor/

    【讨论】:

    • 我的意思是,网站正在调用一个 XHR 请求(wordpess 插件),我想在这个请求完成后执行 X。在 ajax 中很简单,我可以使用 .ajaxComplete(),检查 XHR url 就可以了。 axios中有类似的吗?
    【解决方案2】:

    不,没有。 jQuery 的$.ajax 有一个内置函数,当请求完成时它会触发一个事件。这是ajaxComplete 事件。

    Axios 没有这样的行为,但您可以使用CustomEvent 接口构建自己的行为。或 / 并假设在 document 上有一个方法 axiosSuccess 并调用它。

    const axiosGet = async url => {
      try {
        const response = await axios.get(url)
        const axiosSuccessEvent = new CustomEvent('axiossuccess', {
          detail: { url, response }
        })
        document.dispatchEvent(axiosSuccessEvent)
        if (typeof document.axiosSuccess === 'function') {
          document.axiosSuccess({ url, response })
        }
        return response
      } catch (error) {
        console.log(error)
      }
    }
    

    然后在文档上监听你自己的事件。

    document.addEventListener('axiossuccess', event => {
      const { detail } = event
      const { url, response } = detail
      console.log(url, response)
    })
    
    document.axiosSuccess = ({ url, response }) => {
      console.log(url, response)
    }
    
    axiosGet('https://stackoverflow.com/questions/63998921/')
    

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 1970-01-01
      • 2016-08-30
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多