如何将函数的结果保存到txt文件中?

时间:2019-04-15 16:30:06

标签: javascript php html function variables

我正在尝试从测验中获取数据,然后使用php将其输入到txt文件中。这是我的测验代码:

 function check(){
    var question1=document.quiz.question1.value;
      if (question1=="Yes"){
            correct++;
      }
    document.getElementById("number_correct").innerHTML="Score "+correct+" /10";
    }

在我的html文档上单击一个按钮后,我需要在txt文档中输入number_correct的值。这是我的PHP:

    <?php

    if(isset($_POST['number_correct']))
{
$data=$_POST['number_correct'];
$fp = fopen('results.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>

在这里我的按钮:

<div class="wrapper">
    <form class="frm1" method="post">
       <input class="form-control" id="button" type="button"  value="Submit" onclick="check();"><br>

      <p methods="post" id="number_correct" name="number_correct">
  </p></form><
   </div>

我的问题是,一旦单击按钮并返回number_correct的值,它就不会写入reuslts.txt。

1 个答案:

答案 0 :(得分:-1)

    let download = (stringContents, fileName) => {
        const blob = new Blob([stringContents], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
    };

    let results = 'Congratulations! You got 9 questions right... out of 150 :(';
    download(results, 'results.txt');