download file using an ajax request

后端 未结 12 2359
旧时难觅i
旧时难觅i 2020-11-21 23:46

I want to send an \"ajax download request\" when I click on a button, so I tried in this way:

javascript:

var xhr = new XMLHttpRequest();
xhr.open(\         


        
12条回答
  •  别跟我提以往
    2020-11-22 00:41

    Your needs are covered by window.location('download.php');
    But I think that you need to pass the file to be downloaded, not always download the same file, and that's why you are using a request, one option is to create a php file as simple as showfile.php and do a request like

    var myfile = filetodownload.txt
    var url = "shofile.php?file=" + myfile ;
    ajaxRequest.open("GET", url, true);
    

    showfile.php

    where file is the file name passed via Get or Post in the request and then catch the response in a function simply

    if(ajaxRequest.readyState == 4){
                            var file = ajaxRequest.responseText;
                            window.location = 'downfile.php?file=' + file;  
                        }
                    }
    

提交回复
热议问题