我可以从ajax请求中删除X-Requested-With标头吗?

发布于 2024-09-11 19:29:17 字数 198 浏览 8 评论 0原文

我想知道是否有人有尝试从 jquery(或纯 JS)发出的 ajax 请求中删除“X-Requested-With”标头的经验。是否可以?

第二部分:你知道油脂猴的ajax请求是否设置了这个头吗?

感谢

标题如下所示:

X-Requested-With XMLHttpRequest

I wanted to know if anyone has had experience with trying to remove the 'X-Requested-With' header from the ajax request made by jquery (or plain JS). is it possible?

2nd part: do you know if Grease Monkey's ajax requests set this header?

Thanks

header looks like this:

X-Requested-With XMLHttpRequest

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

红焚 2024-09-18 19:29:17

@vamp 提出的在 jQuery 中删除标头的解决方案是正确的,但正如其他人所说,它仍然会导致发送空的 X-Requested-With 标头。

beforeSend 回调接收 jQuery 的 XHR 对象 (jqXHR),而不是实际的 XMLHttpRequest 对象 (xhr),该对象直到调用 beforeSend 后才被实例化。

jqXHR 中的 setRequestHeader 方法将标头添加到对象中,然后在将 X-Requested-With 条目添加到标头对象之后,稍后使用同名的 xhr 方法对该对象进行迭代。

这是 jQuery 中发生这种情况的部分:

if ( !options.crossDomain && !headers["X-Requested-With"] ) {
    headers["X-Requested-With"] = "XMLHttpRequest";
}

for ( i in headers ) {
    xhr.setRequestHeader( i, headers[ i ] );
}

这会导致问题:如果您不指定 X-Requested-With 标头,那么 jQuery 会指定(除非 crossDomain 设置评估为 false,但这可能不是所需的解决方案) 。然后它立即设置 xhr 标头,该标头无法取消设置。


为了防止使用 jQuery.ajax 发送 X-Requested-With 标头:

jQuery.ajax 提供了一个设置 xhr,它会覆盖 jQuery 用于创建 XMLHttpRequest 对象的内置工厂方法。通过包装此工厂方法,然后包装浏览器的本机 setRequestHeader 方法,可以忽略来自 jQuery 的用于设置 X-Requested-With 标头的调用。

jQuery.ajax({

    url: yourAjaxUrl,

    // 'xhr' option overrides jQuery's default
    // factory for the XMLHttpRequest object.
    // Use either in global settings or individual call as shown here.
    xhr: function() {
        // Get new xhr object using default factory
        var xhr = jQuery.ajaxSettings.xhr();
        // Copy the browser's native setRequestHeader method
        var setRequestHeader = xhr.setRequestHeader;
        // Replace with a wrapper
        xhr.setRequestHeader = function(name, value) {
            // Ignore the X-Requested-With header
            if (name == 'X-Requested-With') return;
            // Otherwise call the native setRequestHeader method
            // Note: setRequestHeader requires its 'this' to be the xhr object,
            // which is what 'this' is here when executed.
            setRequestHeader.call(this, name, value);
        }
        // pass it on to jQuery
        return xhr;
    },

    success: function(data, textStatus, jqXHR) {
        // response from request without X-Requested-With header!
    }

    // etc...

});

The solution for removing the header in jQuery proposed by @vamp is on the right track, but as others have stated it will still result in an empty X-Requested-With header being sent.

The beforeSend callback receives jQuery's XHR object (jqXHR), rather than the actual XMLHttpRequest object (xhr), which is not even instantiated until after beforeSend is called.

The setRequestHeader method in jqXHR adds headers to an object, which is then iterated later using the xhr method of the same name, just after adding the X-Requested-With entry to the headers object.

Here's the part in jQuery where this is happening:

if ( !options.crossDomain && !headers["X-Requested-With"] ) {
    headers["X-Requested-With"] = "XMLHttpRequest";
}

for ( i in headers ) {
    xhr.setRequestHeader( i, headers[ i ] );
}

Which leads to the problem: If you don't specify the X-Requested-With header, then jQuery will (unless the crossDomain setting evaluates false, but that may not be the desired solution). It then immediately sets the xhr headers, which can not be unset.


To prevent sending the X-Requested-With header with jQuery.ajax:

jQuery.ajax provides a setting, xhr, which overrides jQuery's built-in factory method for creating the XMLHttpRequest object. By wrapping this factory method, and then wrapping the browser's native setRequestHeader method, the call from jQuery to set the X-Requested-With header can be ignored.

jQuery.ajax({

    url: yourAjaxUrl,

    // 'xhr' option overrides jQuery's default
    // factory for the XMLHttpRequest object.
    // Use either in global settings or individual call as shown here.
    xhr: function() {
        // Get new xhr object using default factory
        var xhr = jQuery.ajaxSettings.xhr();
        // Copy the browser's native setRequestHeader method
        var setRequestHeader = xhr.setRequestHeader;
        // Replace with a wrapper
        xhr.setRequestHeader = function(name, value) {
            // Ignore the X-Requested-With header
            if (name == 'X-Requested-With') return;
            // Otherwise call the native setRequestHeader method
            // Note: setRequestHeader requires its 'this' to be the xhr object,
            // which is what 'this' is here when executed.
            setRequestHeader.call(this, name, value);
        }
        // pass it on to jQuery
        return xhr;
    },

    success: function(data, textStatus, jqXHR) {
        // response from request without X-Requested-With header!
    }

    // etc...

});
一江春梦 2024-09-18 19:29:17

为什么不呢?
尝试:

(function(){
    $.ajaxSettings.beforeSend=function(xhr){
        xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
    };
})(jQuery);

祝你好运!

why not?
try:

(function(){
    $.ajaxSettings.beforeSend=function(xhr){
        xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
    };
})(jQuery);

good luck!

深爱成瘾 2024-09-18 19:29:17

要使用 jQuery 执行此操作,请将您的请求设置为跨域。示例:

server.php

<?='<pre>'.print_r($_SERVER,1);?>

client.js

$.ajax({ url: 'server.php', crossDomain: true }).success(function(r){document.write(r)})

To do this with jQuery, set your request as cross-domain. Example:

server.php

<?='<pre>'.print_r($_SERVER,1);?>

client.js

$.ajax({ url: 'server.php', crossDomain: true }).success(function(r){document.write(r)})
回忆躺在深渊里 2024-09-18 19:29:17

“第二部分:你知道油猴的ajax请求是否设置了这个标头吗?”

不,Greasemonkey 的 GM_xmlhttpRequest() 不会设置此标头(尽管您可以当然要加上)。

GM_xmlhttpRequest() 发出的默认请求看起来就像普通的浏览器请求。
例如:

GM_xmlhttpRequest
({
    method:     "GET",
    url:        "http://google.com/",
    onload:     function(response) {alert(response.responseText); }
});

对于我的数据包嗅探器来说,看起来像这样:

GET / HTTP/1.1
    Request Method: GET
    Request URI: /
    Request Version: HTTP/1.1
Host: google.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: UTF-8,*
Keep-Alive: 115
Connection: keep-alive
Cookie: blah, blah, blah, blah, blah...

"2nd part: do you know if Grease Monkey's ajax requests set this header?"

No, Greasemonkey's GM_xmlhttpRequest() does not set this header (although you can certainly add it).

The default request issued by GM_xmlhttpRequest() looks just like a normal browser request.
For example:

GM_xmlhttpRequest
({
    method:     "GET",
    url:        "http://google.com/",
    onload:     function(response) {alert(response.responseText); }
});

Looks like this to my packet sniffer:

GET / HTTP/1.1
    Request Method: GET
    Request URI: /
    Request Version: HTTP/1.1
Host: google.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: UTF-8,*
Keep-Alive: 115
Connection: keep-alive
Cookie: blah, blah, blah, blah, blah...
几度春秋 2024-09-18 19:29:17

jQuery 目前没有公开执行此操作的方法,不久前有一张票< /a> 与 Firefox 错误相关,但他们没有将其作为一个选项,而是修复了 Firefox 中的错误问题。

如果您好奇,您可以看到它在此处添加的位置,但如果不编辑/覆盖 jQuery 核心,则无法删除它: http://github.com/jquery/jquery/blob/master/src/ajax.js#L370

jQuery doesn't expose a method to do this at the moment, there was a ticket on it a while back related to Firefox errors, but rather than making it an option, they fixed the error issue in Firefox.

If you're curious, you can see where it's added here, but you can't remove it without editing/overriding jQuery core: http://github.com/jquery/jquery/blob/master/src/ajax.js#L370

阪姬 2024-09-18 19:29:17

你可以考虑这个:

$.ajax({
  url: 'http://fiddle.jshell.net/favicon.png',
  beforeSend: function( xhr ) {
    xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
  },
  success: function( data ) {
    if (console && console.log){
      console.log( 'Got data without the X-Requested-With header' );
    }
  }
});

You may consider this:

$.ajax({
  url: 'http://fiddle.jshell.net/favicon.png',
  beforeSend: function( xhr ) {
    xhr.setRequestHeader('X-Requested-With', {toString: function(){ return ''; }});
  },
  success: function( data ) {
    if (console && console.log){
      console.log( 'Got data without the X-Requested-With header' );
    }
  }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文