dom*_*nho 7 javascript django jquery file download
我有通过电话提交给django服务器的表格.
$("#my_form").submit();
Run Code Online (Sandbox Code Playgroud)
它通过执行以下代码返回xml文件:
content = some_data_retrieved_from_database_as_xml()
response = HttpResponse(content, content_type='text/xml')
response['Content-Disposition'] = 'attachment; '
response['Content-Disposition'] += 'filename=my_file.xml'
response['Content-Encoding'] = 'UTF-8'
return response
Run Code Online (Sandbox Code Playgroud)
谷歌浏览器只下载此文件,但我想注册额外的回调函数,称为myFunction(数据).
Chrome应下载此文件,然后调用myFunction(此xml文件).
我试过这段代码,但它不起作用:
$("#my_form").bind('ajax:complete', myFunction);
Run Code Online (Sandbox Code Playgroud)
我也尝试使用$ .post,但之后只调用了回调函数,不幸的是我的文件没有被下载.
因此,您想要post异步下载返回的文件,并执行回调。一种可能性是“伪造”下载链接:
$.post(POST_URL, POST_DATA, function(response) {
var a = document.createElement('a');
a.setAttribute('href', 'data:'
+ response.contentType
+ ';charset='
+ response.inputEncoding
+ ','
+ new XMLSerializer().serializeToString(response));
a.setAttribute('download', DOWNLOAD_FILENAME);
a.click();
// file download triggered
myFunction();
// additional callback action
});
Run Code Online (Sandbox Code Playgroud)
正如Zoran Majstorovic在他的评论中提到的,你可以尝试这个 jQuery 插件:http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
只需包含来源,然后
$.fileDownload(POST_URL, {
httpMethod: "POST",
successCallback: myFunction
});
Run Code Online (Sandbox Code Playgroud)
为了安全起见,您需要预先设置cookie
Set-Cookie: fileDownload=true; path=/
Run Code Online (Sandbox Code Playgroud)