我正在尝试使用浏览器监听调整大小事件,并且越过阈值< 48 rem,发送“xs”=> exta服务器的小请求标头。相反,对于> 48 rem,将发送“sm”=>小
到目前为止,想出了这个 -if (matchMedia) {
var mq = window.matchMedia("(max-width: 48rem)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is less than 48rem
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
// in this case I'm injecting an access token (eg. accessToken) in the request headers before it gets sent
this.setRequestHeader('x-size-token', ' ');
this.setRequestHeader('x-size-token', "xs");
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
} else {
// window width is at least 48rem
(function(send) {
XMLHttpRequest.prototype.send = function(data) {
// in this case I'm injecting an access token (eg. accessToken) in the request headers before it gets sent
this.setRequestHeader('x-size-token', ' ');
this.setRequestHeader('x-size-token', "sm");
send.call(this, data);
};
})(XMLHttpRequest.prototype.send);
}
}
以这种方式附加到请求标头:
sm
xs,sm
sm,xs,sm
所以基本上,它不是一个旧的,而是它似乎是附加它。
他们的方式只有一件事情发送到requestHeader,xs / sm?
修改
根据一些重新加载每个resize事件的建议,它确实有效但我无法重新加载每个resize事件,因为有很多状态可能会丢失:
$(window).on('resize',function(){location.reload();});
答案 0 :(得分:0)
对我来说似乎有用的是:
function WidthChange(mq) {
if (mq.matches) {
// window width is less than 48rem
$.ajaxSetup({
headers : {
"x-size-token" : "xs"
}
});
} else {
// window width is at least 48rem
$.ajaxSetup({
headers : {
"x-size-token" : "sm"
}
});
}
}
因此,我没有拦截ajax调用并在vanilla JS中设置请求标头,而是使用jquery ajaxSetup为我设置标头,现在我发现在调整大小时即使没有重新加载,下一个ajax请求也会使用正确的值,而不会附加到旧的:
xs
sm
xs