Download CSV file using “AJAX”

后端 未结 6 1102
感情败类
感情败类 2020-11-29 02:22

I\'m trying to accomplish a fairly simple task for my website, but I\"m not sure exactly how to go about it. I want the user to be viewing a table, then click a button, at w

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 02:59

    The best way to accomplish this is to use a Data URI as follows:

    1. Make the AJAX call to the server as per normal
    2. Generate the CSV on the server-side
    3. Return the data (either bare or inside a JSON structure)
    4. Create a Data URI in Javascript using the returned data
    5. Set window.location.href to the Data URI

    See this link for instructions (paragraph #3, specifically): http://en.wikipedia.org/wiki/Data_URI_scheme

    This way, you don't need to save any files on the server, and you also don't need to use iframes or hidden form elements or any such hacks.

提交回复
热议问题