eye*_*aul 14 javascript ajax jquery html5
我有一个ajax调用,我使用jQuery.ajax()向mvc操作发出请求.这一切都很好.但是由于某些表单具有文件控制,我将其从使用jQuery.ajax()更改为使用XMLHttpRequest使用HTML5 File API发送它.
由于进行此更改,MVC操作方法不再将其视为ajax请求.使用Fiddler2我注意到它不再在请求中添加"X-Requested-With:XMLHttpRequest",我认为这是问题所在.
我试图发送的表单中没有文件输入,只有普通的文本框等,但我试图保持方法通用处理两者.以下是我用来发送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);
Run Code Online (Sandbox Code Playgroud)
此代码是在我遇到Darin Dimitrov提供解决方案的问题后提供的,因此我可以通过ajax发送文件输入.
有什么想法为什么这个请求不会发送ajax调用的标头?
sob*_*evn 10
检测我的请求是否有问题我遇到了麻烦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();
Run Code Online (Sandbox Code Playgroud)
经过测试Flask.
| 归档时间: |
|
| 查看次数: |
19408 次 |
| 最近记录: |