我目前正在使用以下JS代码来执行我的Ajax调用:
var ajax = {};
ajax.x = function () {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
我目前有这个小片段调用我的控制器的动作并将输入文件发送到控制器:
function UpdateChapterText() {
try {
document.getElementById("chapterTextInput").value = "";
} catch (e) { }
ajax.post('/Create/ImportFromFile', document.getElementById("chapterFile"), function (data, e) {
document.getElementById("chapterTextInput").value = data;
});
}
带有“chapterFile”作为ID的元素是type =“file”的输入元素。这是我的控制器:
[HttpPost]
public ActionResult ImportFromFile(HttpPostedFileBase chapterFile)
{
string path = Path.GetFileName(chapterFile.FileName);
}
但是,在调试之后,看起来HttpPostedFileBase chapterFile始终保持为null。我完全错误地发送了这个元素吗?
感谢。