2012-04-15 71 views
3
$.ajax({ 
        type: "POST", 
        url: "processform.php", 
        dataType: "json", 
        data: {name: name, email: email, city: city, country: country, day: day, month: month, year: year} 
        }).done(function(msg){ 

         if(msg.success == 1){ 
          $("#success_msg").append('<p>'+msg.message+'</p>'); 
          window.location.href = './music/song.mp3'; 
         } 

        }); 

上面的代码只是用音乐播放器加载新页面。我希望它像文件一样下载。在ajax调用完成后开始下载文件

回答

3

你可以通过PHP做到这一点,创建正确的头一个PHP文件,比重定向到该页面时,它会强制浏览器下载文件。

<?php 
header('Content-disposition: attachment; filename=song.mp3'); 
header('Content-type: audio/mpeg3'); 
readfile('song.mp3'); 
?> 
+0

pecl_http中的http_send_file非常有用 - 为范围请求和http_match_etag启用自动响应304(未修改)。 http://php.net/manual/en/function.http-send-file.php和http://php.net/manual/en/function.http-match-etag.php – Olli 2012-04-15 13:26:17

0

这是浏览器的依赖。如果您的浏览器有媒体插件,它可能直接在浏览器中打开媒体文件,而不是提供下载对话框。

3

尝试做这样:

header("Content-Disposition: attachment; filename=somefile.mp3;"); 
+0

当然,这里假设服务器端的PHP脚本。 – Olli 2012-04-15 13:24:32

+0

是的即时通讯使用php – Adam 2012-04-15 13:28:05

+0

我会在哪里放这个代码?在我的processform.php? – Adam 2012-04-15 13:30:06

1

如果放弃自动化Ajax调用后下载, 你可以做到这一点。浏览器将以自己的方式处理这种情况。

$.ajax({ 
       type: "POST", 
       url: "processform.php", 
       dataType: "json", 
       data: {name: name, email: email, city: city, country: country, day: day, month: month, year: year} 
       }).done(function(msg){ 

        if(msg.success == 1){ 
         $("#success_msg").append('<p>'+msg.message+'</p>'); 
         // window.location.href = './music/song.mp3'; 
         $('<a/>', {target:'_blank', href:'./music/song.mp3'}).appendTo($("#success_msg")).html('Click To Download <Filename>'); 
        } 

       });