如何将html页面的textarea内容保存到文件中并使用ajax(没有JQuery)将其加载到PHP服务器页面? Html页面将是这样的:
<html>
<body>
<textarea id="editor"></textarea>
</body>
</html>
答案 0 :(得分:1)
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;
}
}
?>
?>