2

I apologize in advance for the confusing question wording, but I couldn't figure out how to put this.

I essentially have a string in a database that I intend to make available for user download. How would I go about doing this?

I was attempting to use ajax, but I wasn't sure how to go about it.

The following jquery code is executed when the download link is pressed

$.ajax({

    url: 'index.php/script/downloadFile',
    type: 'post',
    data: {name: $(this).text()}

});

The relevant PHP code looks like:

public function downloadScript(){

    $name = $_POST['name'];

    $filename = $name . ".txt";
    $string = //String that comes from database using name to create query
    $filename = $name . ".txt";

    header('Content-type: text/plain');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header("Content-Length: " . strlen($string));
    header("Connection: close");

    echo $string;
}

Essentially, I want the string to be there for a user to download as a text file. I didn't know if AJAX was the right way to do this or if there was a better way to do the same task. (I was assuming the better way would be to incorporate a hidden iframe somehow)

For a little more information, I have a list of elements:

  • John
  • Jeff
  • Joe
  • Jack
  • When one is clicked, I want to send the text of that element's name to the php file to form the query.

    That's why I don't have a simple href setup to start the file download.

    EDIT:

    While I'm at it, is there anyway for me to get more than one of these files, say there are multiple strings that are returned from the database, save them as separate text files, zip them up, and send them to the user? Or, would that require saving to the server?

    Any help is appreciated!

    4

    1 回答 1

    3

    你可以把它做成一个链接

    <ul>
        <li class="click_link">John</li>
        <li class="click_link">Bob</li>
    </ul>
    
    <script>
    $('li').click(function(e) {
        window.location.href = 'getfile.php?name=' + $(this).text();
    });
    </script>
    

    然后将您的更改$_POST$_GET.

    只要您的标题设置正确,这将下载文件。

    于 2012-07-13T19:29:10.897 回答