問題描述
我正在使用 XMLHttpRequest
將文件從 javascript
代碼發送到 django 視圖
.我需要檢測該文件是否已被發送或如果發生錯誤.我使用 jquery 編寫以下 javascript.
I am using XMLHttpRequest
to send a file from javascript
code to a django view
.I need to detect,whether the file has been sent or if some error occurred.I used jquery to write the following javascript.
理想情況下,我想向用戶顯示文件未上傳的錯誤消息.有沒有辦法在 javascript
中做到這一點?
Ideally I would like to show the user an error message that the file was not uploaded.Is there some way to do this in javascript
?
我試圖通過從 django view
返回 success/failure
消息來做到這一點,將 success/failed 消息
作為 json
并從 django 視圖
發回序列化的 json.為此,我制作了 xhr.open()
non-asynchronous
.我試圖打印 xmlhttpRequest
對象的 responseText
. console.log(xhr.responseText)
顯示
I tried to do this by returning a success/failure
message from django view
, putting the success/failed message
as json
and sending back the serialized json from the django view
.For this,I made the xhr.open()
non-asynchronous
. I tried to print the xmlhttpRequest
object's responseText
.The console.log(xhr.responseText)
shows
response= {"message": "success"}
我想知道的是,這是否是正確的方法.在許多文章中,我發現警告
What I am wondering is,whether this is the proper way to do this.In many articles,I found the warning that
不推薦使用 async=false
Using async=false is not recommended
那么,有沒有什么辦法可以在保持xhr.open()
異步的同時查出文件是否已經發送?
So,is there any way to find out whether the file has been sent,while keeping xhr.open()
asynchronous?
$(document).ready(function(){
$(document).on('change', '#fselect', function(e){
e.preventDefault();
sendFile();
});
});
function sendFile(){
var form = $('#fileform').get(0);
var formData = new FormData(form);
var file = $('#fselect').get(0).files[0];
var xhr = new XMLHttpRequest();
formData.append('myfile', file);
xhr.open('POST', 'uploadfile/', false);
xhr.send(formData);
console.log('response=',xhr.responseText);
}
我的 django
視圖從表單數據中提取文件并寫入目標文件夾.
My django
view extracts file from form data and writes to a destination folder.
def store_uploaded_file(request):
message='failed'
to_return = {}
if (request.method == 'POST'):
if request.FILES.has_key('myfile'):
file = request.FILES['myfile']
with open('/uploadpath/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
message="success"
to_return['message']= message
serialized = simplejson.dumps(to_return)
if store_message == "success":
return HttpResponse(serialized, mimetype="application/json")
else:
return HttpResponseServerError(serialized, mimetype="application/json")
我在 @FabrícioMatté 的幫助下完成了這項工作
I got this working with the help of @FabrícioMatté
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
var data = $.parseJSON(xhr.responseText);
var uploadResult = data['message']
console.log('uploadResult=',uploadResult);
if (uploadResult=='failure'){
console.log('failed to upload file');
displayError('failed to upload');
}else if (uploadResult=='success'){
console.log('successfully uploaded file');
}
}
}
推薦答案
XMLHttpRequest
對象包含 status
和 readyState
屬性,您可以在 xhr.onreadystatechange
事件中進行測試以檢查您的請求是否成功.
XMLHttpRequest
objects contain the status
and readyState
properties, which you can test in the xhr.onreadystatechange
event to check if your request was successful.
這篇關于如何確定 XMLHttpRequest.send() 是否有效的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!