javascript - 按下按钮时写入文件

标签 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>

更新! 这些答案实际上根本不起作用..不确定它是否是我托管的服务器或什么,但是是的,它们根本不起作用..有什么想法吗?

最佳答案

创建一个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>

关于javascript - 按下按钮时写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20947139/

相关文章:

javascript - 使用 jQUERY onclick 后从链接更改 html 文本

javascript - 将 JSON 对象发送到 Web 服务时 $.ajax 函数失败

java - 在 JEditorPane 中编辑 html 内容

javascript - 通过使用 JS 单击另一个按钮类型输入,将值从输入复制到剪贴板

html - 将两个 div 放在一个 div 容器中?

javascript - AngularJS 和 Node.js 与 ExpressJS 集成

丹麦语字符串的 JavaScript UTF-8 编码问题

php - 对连接中的选择结果进行计数

php - 从数组中删除周末

javascript - (SystemJS)XHR错误@ angular/commobundles/common.umd.js/http未找到