[英]Save content of textarea to file and load from PHP server page
how to save content of textarea of html page into a file and load it in PHP server page using ajax (no JQuery)?? 如何将HTML页面的textarea内容保存到文件中,并使用ajax(无JQuery)将其加载到PHP服务器页面中? Html page will be like this : HTML页面将如下所示:
<html>
<body>
<textarea id="editor"></textarea>
</body>
</html>
1.This will give you the structure for your application and please note this code has not been tested. 1.这将为您提供应用程序的结构,请注意,此代码尚未经过测试。
Server.php 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.