2017-04-18 45 views
0

我有一个按钮在客户端下载docx文件。该文件是用PHPWord生成的。在Chrome中它是工作,但不能在Firefox:XMLHttpRequest在Firefox中不起作用

JS:

var req = new XMLHttpRequest(); 
req.open("POST", "/vendor/gendocx.php", true); 
req.responseType = "blob"; 

req.onload = function (event) { 
    var blob = req.response; 
    console.log(blob.size); 
    console.log(blob); 
    var link=document.createElement('a'); 
    link.href=window.URL.createObjectURL(blob); 
    link.download="TEST_this out.docx"; 
    link.click(); 
}; 

req.send(content); 

PHP:

$filename = 'TEST_this out'; 

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpword, 'Word2007'); 

header("Content-Description: File Transfer"); 
header('Content-Disposition: attachment; filename="' . $filename . '"'); 
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); 
header('Content-Transfer-Encoding: binary'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Expires: 0'); 

$objWriter->save($filename); 
$objWriter->save("php://output"); 

exit; 

我已经尝试过在这个网站的其他解决方案,但都没有成功。希望你能帮助我解决这个问题。

没有错误信息。这是blob

enter image description here

+2

“不工作”不是一个好问题陈述。控制台中显示哪些错误消息?当您添加'console.log'语句时,哪些代码行成功运行? – Quentin

+0

我会发现Chrome和Firefox在这里以不同的方式处理Ajax提取令人惊讶(但并非不可能)。我不会惊讶地发现,他们不同地处理'.download'和/或自动'.click()'。失败发生在哪里? 'onload'是否运行?所有代码均已成功运行,并且在Chrome中运行的代码为 – apsillers

+0

。它出现在浏览器底部的常用按钮来打开文件。但在Firefox中,它不幸没有任何东西。控制台没有错误,状态码是200。 – moody

回答

0

我得到了它的结果。

显然Firefox上我必须添加document.body.appendChild(a)到DOM。

req.onload = function (event) { 
    var blob = req.response; 
    console.log(blob.size); 
    console.log(blob); 
    var link=document.createElement('a'); 
    document.body.appendChild(link); 
    link.href=window.URL.createObjectURL(blob); 
    console.log(link.href); 
    link.download="TEST_this_out.docx"; 
    link.click(); 
    setTimeout(function(){ 
     document.body.removeChild(link); 
    }, 500) 
}; 

非常感谢您的帮助!

相关问题