ページ全体を更新せずに、jquery ajaxを使ってテキストエリアを更新することができます。 index.php(私の例ではここ)のsave changes
をクリックすると、テキストエリアの値がid="demo"
で取得され、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
:
大きな速い茶色の黒いキツネは、のろまなイヌに飛びかかりました。
これがあなたに役立つことを願っています。注:これは単なる実用的なコードであり、学習目的のみです。したがって、セキュリティチェックとデータ検証は保証されません。
もちろん、「保存」ボタンのクリックイベントにハンドラを付加するだけで、テキストエリアの値を受け取り、サーバーにajaxリクエストを送信するだけです。そこにペイロードを受け取り、それを保存する "保存"スクリプトがあります(たぶんPHPなどで)。 – arkascha
@arkaschaさて、私はそれを調べて試してみます。ありがとうございました – l00kitsjake