简体   繁体   English

如何在JavaScript中将AJAX输出流式传输到文件下载?

[英]How to stream AJAX output to a file download in Javascript?

We have an REST API emitting JSON from where we can source data (using AJAX). 我们有一个REST API发出JSON,我们可以从中获取数据(使用AJAX)。 What we want to do is to be able to do AJAX calls where each call fetches a small chunk of data (say 5000 rows or so), and then have it written out to a CSV file on the browser as a download. 我们想要做的是能够进行AJAX调用,其中每个调用获取一小块数据(比如5000行左右),然后将其写入浏览器上的CSV文件作为下载。

It seems that if we have all the data in JS memory, then writing it out to CSV file is not hard, but if we want to write out 100K records, then we are forced to fetch all 100K in one shot and then produce the file in one go. 似乎如果我们将所有数据都存储在JS内存中,那么将其写入CSV文件并不难,但如果我们要写出100K记录,那么我们将被迫一次性获取所有100K,然后生成文件一气呵成。

Instead, we feel it would be much gentler on both server and client to download small chunks and stream it out to the file download. 相反,我们觉得在服务器和客户端上下载小块并将其流式传输到文件下载会更加温和。 Is there a way to do it? 有办法吗?

(We are presently using jQuery 2.0.0, but don't mind using a different library to get this done) (我们目前正在使用jQuery 2.0.0,但不介意使用不同的库来完成这项工作)

Basically you are looking for paging of record...for this you can do 基本上你正在寻找记录的分页...为此你可以做到

  1. Find total number of records in database 查找数据库中的记录总数
  2. Than divide your records/no of calls 比划分你的记录/没有电话
  3. Merge all the data coming from different calls 合并来自不同呼叫的所有数据

for making multiple call using jquery you can do like this 使用jquery进行多次调用,你可以这样做

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});

in code there are multiple ajax call and at last it merging data ...that same thing on server side you have to do if you are using C# than TPL (Task parellel library) is good option...for each call you need to call with the page number 在代码中有多个ajax调用,最后它合并数据......如果你使用C#而不是TPL(任务parellel库),那么你必须做的服务器端同样的事情...对于你需要的每个调用拨打页码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM