首页 > 解决方案 > 如何在没有提交按钮的情况下将表单文本区域数据发送到 txt 文件?

问题描述

我希望访问者复制/粘贴或写入文本区域字段的数据保存到网络服务器中的 txt 文件中,但我似乎无法弄清楚。

到目前为止,我有这个 html:

<form class="form-horizontal" role="form" method="post">
      <div class="form-group">
              <label for="data" class="col-sm-2 control-label">The Data</label>
              <div class="col-sm-10">
                         <textarea id="data" onChange="saveToTxt(this); class="form-control"></textarea>
  </div>
</div>

剧本:

<script>
function saveToTxt(fld) {
    const textAreaValue = fld.value;
    // then use textArea variable as container of textarea-content
    // and then treat it as you want.
}
</script>

php文件写入txt文件:

<?php
$handle = fopen("data.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?> 

我似乎无法弄清楚如何在无需访问者按下任何按钮的情况下从表单中调用 php。

有什么建议吗?

编辑:我也试过:

<script>
function editPhrase() {

    set fso = CreateObject("Scripting.FileSystemObject"); 
    set s   = fso.CreateTextFile("filename.txt", True);

    var phraseChange = document.getElementById('data');

    s.writeline("Phrase :" + phraseChange);

    s.writeline("-----------------------------");
    s.Close();
 }
</script>

标签: phphtml

解决方案


尝试这个

`$('#data').on('keyup', function() {
var data = $('#data').val();

$.ajax({
    url: './process.php',
    method: 'POST',
    data: {data: data}
})
});`

PHP

<?php
$text = $_POST['data'];
$handle = fopen("data.txt", "w");
fwrite($handle, $text);
fclose($handle);
?> 

推荐阅读