按下按钮时写入文件

时间:2014-01-06 09:47:45

标签: javascript php html ajax

点击按钮后尝试写入txt文件。不知道怎么做,我的代码不工作。我开始认为我可能需要AJAX?如果是这样,有人可以给我一个正确方向的快速指针吗?请提前谢谢!

这是我的代码:

<?php
 //write to file on button event

function buttonWrite()
{
$filename = 'button.txt';
@ $fp = fopen("messages/".$filename, 'wb');
if (!$fp)
{
    echo '<p><strong>Cannot generate message file</strong></p></body></html>';
    exit;
} 

$outputstring  = 'Hello, i have been generated by the button';

fwrite($fp, $outputstring);
}

?>

<html>

<head>
<title>Button Writer</title>
</head>

<body>
<button type="button" onclick="buttonWrite()">Write to File</button>
</body>

</html>

UPDATE! 这些答案都没有实际工作..不确定它的服务器是否托管或什么,但是,是的,只是不工作..任何想法的家伙?

3 个答案:

答案 0 :(得分:2)

创建一个 PHP文件。让我们说“abc.php”。它包含:

<?PHP
$filename = 'button.txt';
@ $fp = fopen("messages/".$filename, 'wb');
if (!$fp)
{
    echo '<p><strong>Cannot generate message file</strong></p></body></html>';
    exit;
} 
else
{
$outputstring  = 'Hello, i have been generated by the button';
fwrite($fp, $outputstring);
Echo "Message inserted";
}
?>

HTML文件

<html>
<head>
<title>Button Writer</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
</head>

<body>
<button id="button1" type="button">Write to File</button>
</body>
<script type='text/javascript'>
$('#button1').click(function(){
 $.ajax({
 type: "POST",
 url: "abc.php",
 data: "",
 success: function(msg){
     alert(msg);
 },
 error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert("Some error occured");
 }
 });
});
</script>
</html>

答案 1 :(得分:1)

整个代码

Save.php

 <?php
         //write to file on button event

        function buttonWrite()
        {
        $filename = 'button.txt';
        $outputstring = "Hello, i have been generated by the button'\n";
        file_put_contents($filename, $outputstring, FILE_APPEND | LOCK_EX);
        }

        ?>

index.php或index.html

    <html>

        <head>

        </head>

        <body>
<form name="input" action="save.php">
<input type="submit" value="Write to File">
</form>

        </html>

这应该可以使用file_put_contents函数将$ outputstring写入button.txt

答案 2 :(得分:1)

你做错了 - javascript和php无法在HTML中一起执行。 你需要做的是创建:

1)&#34; onclick&#34;按钮事件,它向您的服务器执行AJAX请求。为简单起见,我会在我的示例中使用jQuery

<button id="btn">SAVE FILE</button>

<script type="text/javascript">
  // bind click event to button
  $('#btn').click(function() {
    // send ajax request to save.php (using POST method)
    $.post('save.php', { text: "sample text", function(data) { 
      // output response to console
      console.log(data); 
    });
  });
</script>

2)创建save.php文件 - 它将负责将数据保存到文件

<?php 
  // saving sample text to file (it doesn't include validation!)
  file_put_contents('file.txt', $_POST['text']);

  die('file has been saved');
?>