尝试在单击按钮时写入 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/