MorningStar0
V2EX  ›  问与答

如何解决 js 异步请求逻辑注入

  •  
  •   MorningStar0 · Sep 7, 2018 · 1735 views
    This topic created in 2867 days ago, the information mentioned may be changed or developed.

    昨天看到一个问题,要求在使用 jquery 封装的 ajax 的情况下,且不在业务逻辑里面进行输出。在异步请求发起前输出异步请求内容,包括 asyncType,body,cache 等. import $ from 'jquery'; import beforeAsyncSend from './beforeAsyncSend'; $.ajax(url,{ type: "POST", url: "/test", data: JSON,stringify({ name:'Jean', age:18 }), async: false }) beforAsyncSend(beforeSend){ console.log(beforeSend); } //输出{'asyncType':'POST','body':'{"name":"Jeam","age":"18"}','cache':'true'}

    有一点思路不知道对不对,在$.ajax.prototype 拓展一个函数?

    3 replies    2018-09-07 13:58:05 +08:00
    MorningStar0
        1
    MorningStar0  
    OP
       Sep 7, 2018
    我的排版呢???惊了....
    noe132
        2
    noe132  
       Sep 7, 2018
    一般来说,这个叫拦截器。如 axios 提供了 interceptor 的功能。
    如果没有提供,可以自己 hook 函数
    比如
    const originalAjax = $.ajax
    $.ajax = (...p) => {
    console.log(p)
    originalAjax.apply($, p)
    }
    zzNucker
        3
    zzNucker  
       Sep 7, 2018
    直接 hook 函数就行了,不过要注意 jQuery 有些地方自己实现了逻辑,和 XHR 不太一样
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   987 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 19:47 · PVG 03:47 · LAX 12:47 · JFK 15:47
    ♥ Do have faith in what you're doing.