2012-04-15 77 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>'); 
        } 

       });