在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('

'+msg.message+'

'); window.location.href = './music/song.mp3'; } });

上面的代码只是加载了一个带有音乐播放器的新页面。 我希望它像文件一样下载。

您可以通过PHP完成,使用正确的标头创建一个PHP文件,然后重定向到该页面,它将强制浏览器下载该文件。

  

尝试这样做:

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

如果您在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('

'+msg.message+'

'); // window.location.href = './music/song.mp3'; $('', {target:'_blank', href:'./music/song.mp3'}).appendTo($("#success_msg")).html('Click To Download '); } });

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