2017-01-19 9 views
1

だから私は次のページを持っていると言う。PHPはファイルを提供し、jquery経由でメッセージを送信しますか?

のindex.php

<form action="create_file.php" method="get"> 
    <input type="number" name="num_lines"> 
    <button type="submit">Download File</button> 
<form> 

create_file.php

<?php 
    $num_lines = $_GET['num_lines']; 
    //create a file with $num_lines lines 
?> 

どのように私のことができるようになります

1)$ num_linesラインを持つテキストファイルを作成し、それを果たしますユーザー

2.)jqueryアラートを送信して、ダウンロードが成功したことをユーザーに伝えます。理想的には、メッセージはcreate_file.phpによって作成されます。

すべてindex.phpに留まりますか?

+0

このようなものを試すことができますp://stackoverflow.com/questions/5560373/php-create-file-for-download-without-saving-on-server – VishwaKumar

答えて

1

あなたはajaxを使用できます。 create_file.phpで死ぬのテキストを警告するリンクの下に確認してください。..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<form action="" method="get"> 
    <input type="number" id="numLines" name="num_lines"> 
    <button id="button" type="button">Download File</button> 
<form> 

<script> 
$(document).on('click','#button',function(){ 
var val=$('#numLines').val(); 
$.post('create_file.php',{val:val},function(r){ 
alert(r) 
}); 

}); 
</script> 

create_file.php

<?php 
    $num_lines = $_GET['num_lines']; 
    die($num_lines); 
?> 
0

クライアント側のアプローチたら、それを確認してください。 http://jsfiddle.net/uselesscode/qm5ag/

あるいは、

<?php 
$num_lines = $_GET['num_lines']; 
$ext = '.txt'; 
$tmpfname = tempnam("./", "numLines_"); 
if (file_exists($tmpfname)) { 
    unlink($tmpfname); 
    file_put_contents($tmpfname . $ext, $num_lines); 
    echo json_encode(array('fileUrl' => basename($tmpfname) . $ext)); 
} else { 
    echo 'err'; 
} 
?> 

<!doctype html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<script> 
$(function(){ 
    $.get('create_file.php', {'num_lines': 42}, function(res){ 
    var response = $.parseJSON(res) 

    if(typeof response =='object') { 
     var downloadableFileLink = $('<a></a>').attr('href', response.fileUrl).html("Click here to your file, yo.") 

     $('#downloadTheRapper').append(downloadableFileLink) 
     console.log('Oh snap.') 
    } else { 
     console.log('err') 
    } 
    }); 
}); 
</script> 
</head> 
<body> 
<div id="downloadTheRapper"></div> 
</body> 
</html> 
関連する問題