ajax-hook icon indicating copy to clipboard operation
ajax-hook copied to clipboard

在onreadystatechange函数里打印readyState未出现过 1 的状态

Open yebingo opened this issue 5 years ago • 4 comments

想在readyState为1(open方法已经被调用,但还没调用send方法)时调用setRequestHeader方法设置header,但在onreadystatechange里打印readyState,从未出现过为1的状态,想请教下是什么原因,谢谢。

代码如下: image

以下是在控制台打印的结果: image

yebingo avatar Feb 21 '19 15:02 yebingo

你可以看一下直接使用XmlHttpRequest能否收到1,ajax hook是透明传递的

wendux avatar Feb 22 '19 12:02 wendux

想在readyState为1(open方法已经被调用,但还没调用send方法)时调用setRequestHeader方法设置header,但在onreadystatechange里打印readyState,从未出现过为1的状态,想请教下是什么原因,谢谢。

代码如下: image

以下是在控制台打印的结果: image

+1 需要在状态为1时,修改请求头。

rowthan avatar Apr 09 '19 10:04 rowthan

     let xhrObject = null;
      hookAjax({
        //拦截回调
        onreadystatechange:function(xhr){
          xhrObject = xhr;
        },
        onload:function(xhr){
          console.log("onload called: %O",xhr)
        },
        //拦截方法
        open:function(arg,xhr){
          xhrObject = xhr;
          console.log(xhr.readyState+"open called: method:%s,url:%s,async:%s",arg)
        },
        send:function (xhr) {
          xhrObject.setRequestHeader("LOCATION", window.location.href);
        }
      })

解决办法: 将xhr对象存储起来,在send中使用。

rowthan avatar Apr 09 '19 10:04 rowthan

hook send 第二个参数就是xhr,没必要保存

wendux avatar Apr 24 '19 05:04 wendux