这是我第一次在stackoverflow上写作,所以如果我做错了什么,我很抱歉。
我想把文本区域的内容写入一个文件。有人能写一些代码来保存我的订单吗?我真的不知道该怎么做,我也没有找到任何关于它的帖子。
感谢回复
$file = "file";
$f = fopen($file, "r");
echo '<textarea name="ciao" id="ciao" rows="5" cols="40">';
while ( $line = fgets($f, 1000) ) {
echo $line;
}
fclose($f);
echo '</textarea>';
<textarea type="textarea" id="ciao_hidden" value="ciao_hidden" style="display:none;" ></textarea>
<script type="text/javascript">
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|'n)'s+|'s+(?:$|'n))/g,'').replace(/'s+/g,' ');};
var charfield = document.getElementById("ciao");
var ch = document.getElementById('ciao_hidden');
charfield.onkeydown=function(e){
var str,cv;
if (e.keyCode == "13") {
console.log(charfield.value);
cv = charfield.value;
str = cv.replace(/'n+/g, "<br />");
ch.value = str;
console.log(ch.value);
}
}
</script>
根据你对我最初答案的回复,我得出了以下结论:
test.php
<?php
// Config?
$saveToFile = 'savedText.txt';
// Post Handler
if (count($_POST) && isset($_POST['myText']))
{
file_put_contents($saveToFile, $_POST['myText']);
/*
// Alternate Save Code - the directory you are working with
// must have write permission
$h = @fopen($saveToFile, 'a');
if ($h) {
fwrite($h, $_POST['myText']);
fclose($h);
}
*/
exit('Data Saved.');
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Handle Enter Key In Textarea
$("#myTextarea").keyup(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$.ajax({
type: "POST",
url: 'test.php',
data: { myText: $(this).val() },
success: function(result) {
console.log('Success : ' + result);
}
});
}
});
});
</script>
Enter your text and press enter to save:<br>
<textarea rows="10" cols="50" id="myTextarea"></textarea>
需要考虑的几件事:
- 在多用户环境中,这不是一个好主意。当两个或两个以上的人正在键入时,文件的内容将被最后一个按enter键的用户覆盖
- 这对硬盘不好(I/O太多,为什么不考虑将其保存到数据库中?(
在现代浏览器中,您可以使用javascript下载内容https://developer.mozilla.org/en-US/docs/Web/API/Blob
使用jquery,类似这样的东西会在文本区域后面创建一个<a>
元素,提示用户将文本区域内容下载为文本文件
$('textarea + a').each(function(i){
var txt = new Blob([$(this).prev().val()], {type:'text/plain'});
$(this)
.prop('download', $(this).html())
.prop('href', window.URL.createObjectURL(txt) );
});