0
我正在使用JQuery AJAX请求,它会在完成时触发下载。Jquery启动下载返回'失败:网络错误'
CODE:
$('.getPDF').click(function(){
var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf';
$.ajax({
url: '/formulas/'+ this.id +'/pdf',
type: 'POST',
success: downloadFile(filepath)
});
function downloadFile (path) {
var link = document.createElement('a');
link.href = path;
$(link).attr("download", true);
link.click();
}
});
这将返回在Chrome以下错误:
Failed - Network Error
没有别的显示在控制台中了。下载在Firefox或IE中也不起作用。
我已经成功完成了console.log(filepath)
,并且当它作为URL粘贴到浏览器栏中时,它返回的路径显示正确的文件。
的HTML生成Ajax请求如下:
<a class="pure-button button-success getPDF" id="59ac514a52c93e4aa862fadd">Generate PDF </a>
如果是相关的,服务器端代码一般是这样的:
router.post('/formulas/:id/pdf', function(req, res){
var db = req.db.collection('users');
var id = new ObjectID(req.params.id);
var pointer = {"formulas.$": 1, "_id": 0};
db.aggregate([
{$match: {"formulas.f_id": id}},
{$unwind: "$formulas"},
{$match: {"formulas.f_id": id}},
{$project : {"formulas": 1, "_id": 0}}
]).toArray(function(e, doc){
if (e) {
throw e;
} else {
var html = null;
ejs.renderFile('./views/pdf.ejs', {
project: doc[0].formulas
}, function(err, results){
if (err) {
console.log(err);
}
html = results;
});
var options = { format: 'Letter' };
var path = 'public/pdf/formula-' + req.params.id + '.pdf';
pdf.create(html, options).toFile(path, function(err, results) {
if (err) {
return console.log(err);
}
if (results) {
res.end();
}
});
}
});
});
'downloadFile'不会在成功时被调用,而是马上看到您已经包含圆括号。那应该不重要?你有一条静态路由,它实际上提供了你正在下载的PDF文件 – adeneo
@ adeneo - 是的,我测试了静态路由,并且它正确地提供了文件。 –
你试过添加协议吗?因为'filepath'被用在一个锚href中......也许...'''''''''''var filepath ='http:// localhost:3000/pdf/formula-'+ this.id +'.pdf';' –