JavaScript — как написать (php) веб-приложение для отправки клиенту .txt файл со значениями, которые клиент вставил в окно приглашения JS

Я хочу разработать (игрушечное) приложение для 1), чтобы позволить пользователю заполнить поле приглашения JS парой значений, записать их в файл .txt и 2) отослать последнее обратно пользователю.

Я могу сделать любой из них, но не объединить их в одном приложении.

У меня есть эти два коротких сценария:

main.html

<html>
<head>
<script type="text/javascript">
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
var mail = prompt("Please enter your email", "Harry Potter");
document.getElementById("person").value = person;
document.getElementById("mail").value = mail;
document.getElementById("form").submit();   <<<< NOTE
}

ПРИМЕЧАНИЕ. Кажется, что представление таково, что каким-то образом приводит к сбою readfile (); ниже

 </script>
</head>
<body>

<form id="form" action="minor.php?file=abc.txt" method="post">
<input type="hidden" name="person" id="person" />
<input type="hidden" name="mail" id="mail" />
</form>

<a onclick=myFunction(); href="minor.php?file=abc.txt">see abc.txt</a>';
</body>
</html>

ПРИМЕЧАНИЕ Я попробовал оба action="minor.php?file=abc.txt" а также href="minor.php?file=abc.txt" выше (не оба одновременно!), и в любом случае чего-то не хватает (см. различные выводы, которые я получу ниже)

minor.php

<?php

$file_directory = "Files";
$file = $_GET['file'];
$file_array = explode('/', $file);
file_array_count = count($file_array);
$filename = $file_array[$file_array_count-1];
$file_path = dirname(__FILE__).'/'.$file_directory.'/'.$file;

if (is_writable($file_path)) {
if (!$handle = fopen($file_path, 'a')) {
echo "Cannot open file ($file_path)";
exit;
}

foreach($_POST as $key => $req){  // or use $_REQUEST
if (fwrite($handle, $key."--".$req."\n")== FALSE){
echo "Cannot write to file ($file_path)";
exit;
}
}
fclose($handle);

} else {
echo "The file $file_path is not writable";
}

if(file_exists($file_path)) {
header('Content-type: text/plain');
header("Content-disposition: attachment; filename={$filename}");
readfile($file_path); //Read and stream the file
}
else {
echo "Sorry, the file does not exist!";
}
?>

Это разные результаты, которые я получаю, когда перетасовываю пару данных:

case A
document.getElementById("form").submit(); included
action="" (empty)
href="minor.php?file=abc.txt"----
DO download abc.txt
Nothing written into abc.txt
access.log: "GET .../minor.php?file=abc.txt HTTP/1.1" 200 13

case B
//document.getElementById("form").submit();  // Commented out
action="" (empty)
href="minor.php?file=abc.txt"-----
DO download abc.txt
Nothing written into abc.txt (clear why)
access.log:  "GET .../minor.php?file=abc.txt HTTP/1.1" 200

case C
document.getElementById("form").submit();  included
action="minor.php?file=abc.txt"href="" (empty)
-----
DOES NOT download abc.txt
access.log "GET .../main.html HTTP/1.1" 304 (error??)

Ваша помощь приветствуется.

1

Решение

следующий код делает то, что я искал:

(minor.php, как указано выше, но используйте foreach($_GET ... ) вместо foreach($_POST ... ) )

main.html

<html>
<head>
<script type="text/javascript">
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
var mail = prompt("Please enter your email", "Harry Potter");
document.getElementById("clickhere").innerHTML="";
document.getElementById("mainlink").innerHTML="please download now";
document.getElementById("mainlink").href="minor.php?file=abc.txt&"+"person="+person+"&mail="+mail+"";
document.getElementById('mainlink').click();
}
</script>
</head>
<body>
<div onclick=myFunction(); id="clickhere">click here</div>
<a  href="#" id="mainlink"></a>
</body>
</html>

Я приветствую другие ответы с улучшенным / альтернативным кодом.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector