Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jquery启动下载返回';失败:网络错误';_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript Jquery启动下载返回';失败:网络错误';

Javascript Jquery启动下载返回';失败:网络错误';,javascript,jquery,ajax,Javascript,Jquery,Ajax,我正在使用一个jqueryajax请求,它将在完成后触发下载 代码: $('.getPDF').click(function(){ var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf'; $.ajax({ url: '/formulas/'+ this.id +'/pdf', type: 'POST', success: downloadFile(filepath) }); function

我正在使用一个jqueryajax请求,它将在完成后触发下载

代码:

 $('.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粘贴到浏览器栏时,它返回的路径显示了正确的文件

生成AJAX请求的HTML如下所示:

<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();
      }
    });
   }
  });
});

Ajax成功回调必须是一个函数…
第一个参数可以按照您的意愿命名。。。但将充满Ajax响应

因此,响应将覆盖您的
文件路径
变量…
要避免这种情况,请在回调函数中调用
downloadFile

如果你不需要回答,就忽略它


成功时不会调用
下载文件
,但会立即调用,因为您已经包含了括号。但这并不重要?你有没有一个静态的路径,可以提供你想要的PDF文件download@adeneo-是的,我已经测试了静态路由,它正确地提供了文件。你尝试添加协议了吗?由于
filepath
用于锚href。。。也许<代码>var filepath=http://localhost:3000/pdf/formula-“+this.id+”.pdf”为什么不发布节点如何返回PDF,因为这似乎是错误所在,因此是网络错误?我认为,
filepath
可能会被ajax响应覆盖。。。试试这个:
success:function(response){downloadFile(filepath);}
success: function(response){
  downloadFile(filepath);
}