XMLHtt prequest不添加标题 - &QUOT X-要求,通过:XMLHtt prequest"标题、XMLHtt、prequest、QUOT

2023-09-10 16:26:32 作者:酷炫小祖宗

我有一个Ajax调用,我使用jQuery.ajax()提出请求到MVC的行动。这一切都工作得很好。然而,由于有一个文件控制我使用jQuery.ajax()使用XMLHtt prequest它使用HTML5文件API发送改变它的一些形式。

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.

由于进行此更改的MVC操作方法再也看不到是它作为一个Ajax请求。使用Fiddler2我注意到,它不再添加X-要求,通过:XMLHtt prequest的要求,我想这就是问题所在。

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.

的形式,我想送不具有文件输入在里面,只是正常的文本框等,但我试图保持通用的方法来处理这​​两种。以下是code我用来发送Ajax请求:

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:

// 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);

这code的下一个问题,我有这达林季米特洛夫提供的解决方案来提供,这样我就可以通过AJAX发送文件的输入。

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.

为什么这个请求将不会发送标题为Ajax调用任何想法?

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

推荐答案

X-要求 - 以自动的jQuery补充说。您可以自己用 AjaxRequestObject.setRequestHeader很容易地添加()。 文档

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