![](/img/trans.png)
[英]How to save content from textarea as array, and save in another php file?
[英]Save content of textarea to file and load from PHP server page
如何將HTML頁面的textarea內容保存到文件中,並使用ajax(無JQuery)將其加載到PHP服務器頁面中? HTML頁面將如下所示:
<html>
<body>
<textarea id="editor"></textarea>
</body>
</html>
1.這將為您提供應用程序的結構,請注意,此代碼尚未經過測試。
Server.php
<html>
<script>
var baseUrl="service.php";
function submitFormAjax()
{
var xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var data = document.getElementById('editor').value;
xmlhttp.open("POST",baseUrl,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("action=write&data=" + data);
}
function readDataAjax()
{
var xmlhttp= window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById('editor').value=xmlhttp.responseText;
}
xmlhttp.open("POST",baseUrl,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("action=read");
}
</script>
<body onload="readDataAjax()">
<form method="post">
<textarea id="editor" name="editor"></textarea>
<button onClick="submitFormAjax();return false;">Submit</button>
</form>
</body>
</html>
<?php
$fileName="newfile.txt";
if(isset($_POST['action']))
{
switch($_POST['action'])
{
case 'read';
echo file_get_contents($fileName);
break;
case 'write';
if( isset($_POST['data']))
{
$myfile = fopen($fileName, "w") or die("Unable to open file!");
$txt = $_POST['data'];
fwrite($myfile, $txt);
fclose($myfile);
echo "file successfully saved";
}
break;
}
}
?>
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.