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';' –