tgo*_*es3 2 python django ajax
我有一个问题,我无法在任何地方找到符合我需要的解决方案。
当我点击一个按钮时,我有这个 AJAX 调用:
$.ajax({
type: 'POST',
url: '{% url "tests" %}',
traditional: true,
data : {'mydata': list,"excel": "" },
success: function (data, textStatus) {
//Test
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error " + String(errorThrown) + String(textStatus) + String(XMLHttpRequest.responseText));
}
});
Run Code Online (Sandbox Code Playgroud)
在 views.py 中:
if request.method == "POST" and request.is_ajax():
if 'excel' in request.POST:
data = request.POST.getlist('mydata')
if data:
tests = Test.objects.filter(pk__in=data)
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=Test.xlsx'
xlsx_data = WriteToExcelTests(tests)
response.write(xlsx_data)
return response
Run Code Online (Sandbox Code Playgroud)
如果我不使用 AJAX(因为我有另一个不使用 AJAX 的情况)并且文件已下载到浏览器中,但在这种情况下我无法下载文件,它不会给出任何错误它不下载文件。
如何强制下载文件?
我有同样的问题。感谢这个答案/sf/answers/3303857931/和一点点谷歌搜索,我是这样解决的:
$('#download_btn').on('click', e => {
// random data
let data = 'mydata=foo&excel=bar';
let request = new XMLHttpRequest();
request.open('POST', '{% url "tests" %}', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function (e) {
if (this.status === 200) {
let filename = "";
let disposition = request.getResponseHeader('Content-Disposition');
// check if filename is given
if (disposition && disposition.indexOf('attachment') !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
let blob = this.response;
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
let downloadLink = window.document.createElement('a');
let contentTypeHeader = request.getResponseHeader("Content-Type");
downloadLink.href = window.URL.createObjectURL(new Blob([blob], {type: contentTypeHeader}));
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
} else {
alert('Download failed.')
}
};
request.send(data);
});
Run Code Online (Sandbox Code Playgroud)
我们不能使用 Jquery Ajax 来下载本博文中提到的文件。