The content shared with you in this article is the reason why download requests cannot be sent in ajax. It has a certain reference value. Friends in need can refer to it.
I have been doing file downloads recently and writing in the background. I have a control layer, and I should be able to download files, various files, pictures, excel, etc. if I just walk in.
But at first, the download always fails, and the following garbled code pops up:
Front desk request code:
$('#fileexcel').unbind('click').bind('click',function(){ alert("我要下载了"); $.ajax({ type:'post', url:'media', data:null, async:true, success : function(msg){ alert(msg); } }) })
It seems that there is no problem, but it cannot be downloaded.
I originally thought there was a problem with the backend code, but there are still problems with putting various demos on the Internet.
After struggling for a day, I finally found the problem.
There is a problem with the request method. File download requests cannot be written in ajax!
Just write it as follows:
<a href="/media">点击下载Excel</a> 或者 location.href = '/media';
Click to download this time and the following ideal effect will appear.
Then summarize why the download request cannot be sent in ajax:
Reason: Because of the response, the general request browser will process the response output by the server, such as generating png, file download, etc. However, the ajax request is only a "character type" request, that is, the requested content is stored in text type. The download of the file is in binary form. Although the returned response can be read, it is only read and cannot be executed. To put it bluntly, js cannot call the download processing mechanism and program of the browser.
Related recommendations:
Cannot use ajax to request to download files
The reason why Ajax request cannot download the file
Alternative solution for file download that cannot use ajax
The above is the detailed content of The reason why the download request cannot be sent in ajax. For more information, please follow other related articles on the PHP Chinese website!