Javascript XMLHttpRequest 不添加标头 - “X-Requested-With: XMLHttpRequest”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12533435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:38:34  来源:igfitidea点击:

XMLHttpRequest not adding header - "X-Requested-With: XMLHttpRequest"

javascriptjqueryajaxhtml

提问by eyeballpaul

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 using jQuery.ajax() to using the XMLHttpRequest to send it using the HTML5 File API.

我有一个 ajax 调用,我使用 jQuery.ajax() 向 mvc 操作发出请求。这一切都很好。但是,由于某些表单具有文件控件,我将其从使用 jQuery.ajax() 更改为使用 XMLHttpRequest 以使用 HTML5 文件 API 发送它。

Since making this change the MVC action method no longer see's it as an ajax request. Using Fiddler2 I have noticed that it no longer adds the "X-Requested-With: XMLHttpRequest" to the request and I assume this is the problem.

由于进行此更改,MVC 操作方法不再将其视为 ajax 请求。使用 Fiddler2 我注意到它不再向请求添加“X-Requested-With:XMLHttpRequest”,我认为这是问题所在。

The form I am trying to send does not have a file input in it, only normal textboxes etc, but I was trying to keep the method generic to deal with both. The following is the code I am using to send the ajax request:

我试图发送的表单中没有文件输入,只有普通的文本框等,但我试图保持通用的方法来处理这两种情况。以下是我用来发送ajax请求的代码:

// get the edit tender form
var $Form = $Button.closest('form');
var Url = $Form.attr('action');
var AjaxRequestObject = new XMLHttpRequest();
var FormDataToSend = new FormData();

$Form.find(':input').each(function () {
    if ($(this).is('input[type="file"]')) {
        var files = $(this)[0].files;
        if (files.length > 0) {
            FormDataToSend.append(this.name, files[0]);
        }
    } else {
        FormDataToSend.append(this.name, $(this).val());
    }
});

AjaxRequestObject.open('POST', Url, true);
AjaxRequestObject.onreadystatechange = function () {
    if (AjaxRequestObject.readyState == 4) {
        // handle response.
        if (AjaxRequestObject.status == 200) {
            if (!AjaxErrorExists(AjaxRequestObject.responseText, )) {
                alert("success");
                console.log(AjaxRequestObject.responseText);
            }
            else {
                alert('failure');
            }
        }
        else {
            alert('failure');
        }
    }
};

AjaxRequestObject.send(FormDataToSend);

This code was provided following a problem I had which Darin Dimitrov provided the solution to, so I could send the file inputs by ajax.

此代码是在我遇到 Darin Dimitrov 提供解决方案的问题后提供的,因此我可以通过 ajax 发送文件输入。

Any ideas why this request would not send the header for an ajax call?

任何想法为什么此请求不会发送 ajax 调用的标头?

回答by Niet the Dark Absol

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

X-Requested-With由 jQuery 自动添加。您可以使用AjaxRequestObject.setRequestHeader(). 文档

回答by sobolevn

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

我在检测我的请求是否为ajax. 因此,也许这个示例可以为某人节省一两分钟:

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.

经测试Flask

回答by monstersmart

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

您可以本地覆盖所有 XMLHttpRequest.open 方法调用,并在其中添加 X-Requested-With 标头,例如:

(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');
    });
}());