问题描述
我刚刚在一些ajax代码中发现了一个错误,当上传图片的大小超过我的操作过滤器中设置的大小时,UI'挂起',或者 requestLimits maxAllowedContentLength
。调试告诉我下面的代码用于上传有问题的图像。此项目的所有其他Ajax请求由jQuery ajax处理,具有良好的错误处理,除了此图像上载请求。面对它,我不明白为什么我不能仅仅通过调用已经测试的jQuery ajax代码来替换这个旧的学校代码。有没有什么理由我不能看到,作为一个真正的JS菜鸟,仍然使用这个代码?
I have just found a bug in some ajax code, where the UI 'hangs' when the size of an uploaded image exceeds a size set in my action filter, or in requestLimits maxAllowedContentLength
. Debugging tells me the code below is used to upload the offending image. All other Ajax requests for this project are handled by jQuery ajax, with decent error handling, except this image upload request. In the face of it, I don't see why I can't just replace this old school code with a call to the already tested jQuery ajax code. Is there any reason I can't see, as a real JS noob, for this code still being used?
dataAccess.submitJsonWithFileRequest = function(targetUrl, fileToUpload, onComplete) {
var formData = new FormData();
formData.append(fileToUpload.name, fileToUpload);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonData = jQuery.parseJSON(xhr.responseText);
onComplete(jsonData);
}
};
xhr.open('POST', targetUrl, true);
xhr.send(formData);
};
推荐答案
dataAccess.submitJsonWithFileRequest = function(targetUrl, fileToUpload, onComplete) {
var formData = new FormData();
formData.append(fileToUpload.name, fileToUpload);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
// first check that the readyState is 4 (request completed)
if (xhr.readyState == 4) {
// now check the status
if(xhr.status == 200)
{
var jsonData = jQuery.parseJSON(xhr.responseText);
onComplete(jsonData);
} else {
// there was an error, so status codes could be
// 404 - file not found
// 500 - Server error
// 0 - Request aborted (browser stopped transfer)
}
}
};
xhr.open('POST', targetUrl, true);
xhr.send(formData);
};
这篇关于为什么不使用jQuery Ajax呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!