Ajax and downloading CSV file

前端 未结 2 1731
甜味超标
甜味超标 2020-12-22 01:50

I\'m trying to build a \"Export to CSV\" system using ajax so this is my ajax call

$(document).on(\'click\', \'#export-csv\', function(){
    $.ajax({
              


        
相关标签:
2条回答
  • 2020-12-22 02:22

    Try creating a element with href attribute set to data URI of file using URL.createObjectURL , Blob ; download attribute to set file name for "Save file" dialog

    success: function (data) {
                var resp = data.response;
                var a = $("<a />", {
                   href: "data:text/csv," 
                         + URL.createObjectURL(new Blob([resp], {
                             type:"text/csv"
                           })),
                   "download":"filename.csv"
                });
                $("body").append(a);
                a[0].click();
            }
    
    0 讨论(0)
  • Return the url of the .csv file in your ajax call. Then in your success function put:

    location.href = url;
    

    Just like all file types that are not naturally handled by the browser this will cause the browser to download the file.

    0 讨论(0)
提交回复
热议问题