![](/img/trans.png)
[英]onClick javascript changes are not reflected without reloading page
[英]Save Changes to File Without reloading Page
现在,我有一个HTML文本区域,可从文本文件获取其内容。 我想做的是允许用户在文本区域中编辑文件,当他们按下按钮时,所做的更改将推送到文件中,而无需重新加载整个页面。
我了解仅凭JavaScript不能做到这一点,因为它是一种客户端语言,但是我想可以用AJAX做到这一点? 我在AJAX方面经验不足,因此可能无法正常工作。
为了简单起见,我想远离websockets。
以下是我的PHP textarea代码:
<?php
$myfile = fopen($file, 'a+');
echo "<textarea id='demo'>";
// go through each line in the file, print its contents.
while(!feof($myfile)) {
echo fgets($myfile);
}
echo "</textarea>";
?>
好吧,您有几种简单的方法可以做到这一点。
方法2更优雅。
您无需刷新整个页面即可使用jquery ajax更新textarea。 当您单击index.php上的save changes
(在我的示例中)时,我们通过其id="demo"
获得textarea的值,并将其发送给update.php。 在update.php中,我们使用fwrite()
清除所有现有文本,并将从textarea
获得的新内容写入其中,并像在index.php
一样显示新文本。
所以这是index.php
:
<!DOCTYPE HTML>
<html>
<head>
<title>TextArea Lesson</title>
<style>
div{
margin:0 auto 0;
width:400px;
height:300px;
}
#demo{
margin-left:5px;
width:390px;
height:200px;
}
</style>
</head>
<body>
<div>
<form method="POST">
<fieldset>
<legend>Ajax Update Text Area</legend>
<?php
$myfile = fopen('test.txt', 'r');
echo "<textarea id='demo'>";
// go through each line in the file, print its contents.
while(!feof($myfile)) {
echo fgets($myfile);
}
echo "</textarea><br>";
?>
<input type="submit" id="save" value="Save changes" />
</fieldset>
</form>
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"
integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk="
crossorigin="anonymous"></script>
<script>
//when you click save changes, we get its id="save"
//and prevent default submission
$(document).on("click", "#save", function(e){
e.preventDefault();
//get the textarea data bu its id="demo"
var textdata = $('#demo').val();
mydata= 'testdata='+textdata;
$.ajax({
type:'POST',
data:mydata,
url:'update.php',
success:function(data) {
if(data){
alert('Saved!');
$("#demo").html(data);//load data from update.php
}else{
alert('Update failed');
}
}
});
});
</script>
Update.php
:
<?php
$data_to_write = $_POST['testdata'];
$file_path = 'test.txt';
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);
$myfile = fopen('test.txt', 'r');
while(!feof($myfile)) {
echo fgets($myfile);
}
fclose($myfile);
?>
和test.txt
:
大型的棕色黑狐狸跳过了一条懒狗。
希望对您有所帮助。 注意:这只是一个工作代码,仅供学习之用。 因此,不能确保安全检查和数据验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.