XMLHttpRequest not adding header - “X-Requested-With: XMLHttpRequest”

前端 未结 3 2047
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 02:41

I have an ajax call where I used jQuery.ajax() to make a request to an mvc action. This all worked fine. However due to some forms having a file control I changed it from us

相关标签:
3条回答
  • 2020-12-30 03:10

    You can override natively all XMLHttpRequest.open method calls and add in it X-Requested-With header like:

    (function () {  
    
        // @author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3
    
        if (window.XMLHttpRequest.prototype.onOpen)  {
            return console.log('XMLHttpRequest.onOpen is already defined');
        }
    
        function over(method, on, off) {
    
            var old = window.XMLHttpRequest.prototype[method];
    
            if (!old.old) {
    
                var stack = [];
    
                window.XMLHttpRequest.prototype[on] = function (fn) {
                    if (typeof fn === 'function') {
                        stack.push(fn);
                    }
                }
    
                window.XMLHttpRequest.prototype[off] = function (fn) {
                    for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                        if (stack[i] === fn) {
                            stack.splice(i, 1);
                            break;
                        }
                    }
                }
    
                window.XMLHttpRequest.prototype[method] = function () {
                    var args = Array.prototype.slice.call(arguments);
    
                    var ret = old.apply(this, args);
    
                    for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
                        stack[i].apply(this, args);
                    }
    
                    return ret;
                }
    
                window.XMLHttpRequest.prototype[method].old = old;
            }
        }
    
        over('open', 'onOpen', 'offOpen')
    
        XMLHttpRequest.prototype.onOpen(function () {
            this.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        });
    }());
    
    0 讨论(0)
  • 2020-12-30 03:22

    X-Requested-With is automatically added by jQuery. You can just as easily add it yourself with AjaxRequestObject.setRequestHeader(). Docs

    0 讨论(0)
  • 2020-12-30 03:34

    I was having troubles with detecting if my request was ajax. So, maybe this sample will save someone a minute or two:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET', URL, true);  // `true` for async call, `false` for sync.
    
    // The header must be after `.open()`, but before `.send()`
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    
    xmlhttp.onreadystatechange = function() {
        // 4th state is the last:
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
    };
    xmlhttp.send();
    

    Tested with Flask.

    0 讨论(0)
提交回复
热议问题