悠悠楠杉
网站页面
1.php
<?php
header('content-type: application/json;charset=utf-8');
$wj = '1.txt';
if (!empty($_POST)) {
//插入内容,不加FILE_APPEND,默认值为替换内容
$fp = file_put_contents($wj, $_POST['te'] . "\n", FILE_APPEND);
if ($fp !== false) {
echo json_encode(array('code' => '200', 'msg' => '提交成功'));
} else {
echo json_encode(array('code' => '400', 'msg' => '提交失败'));
}
} else {
if (isset($_GET['te']) && $_GET['te'] == 'hq') {
//获取内容
$str = file_get_contents($wj);
$arr = explode("\n", $str); //把换行转换成数组
// print_r($arr);
echo json_encode($arr);
} else {
echo json_encode(array('code' => '400', 'msg' => '获取失败'));
}
}
1.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Cache-Control" content="no-cache">
<title>PHP利用txt文本存储数据</title>
</head>
<body>
<input type="text" name="te">
<button class="btn">提交</button>
<div class="box"></div>
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert"></script>
<script>
$('.btn').on('click', function() {
var te = $('[name="te"]').val();
if (te == '') {
swal('提示', '请输入内容', 'error');
} else {
$.post('1.php', {
te: te
}, function(ret) {
if (ret.code == 200) {
swal("提示", "提交成功", "success", {
buttons: "确定" //,dangerMode: true //确定按钮变红色
}).then((value) => {
// swal(`The returned value is: ${value}`);
if (value) {
// swal('确定');
location.reload();
} else {
// swal('取消');
location.reload();
}
});
} else {
swal('提示', '提交失败', 'error');
}
})
}
})
$.get('1.php', {
te: 'hq'
}, function(ret) {
console.log(ret);
if (ret.code == 400) {
swal('提示', ret.msg, 'error');
} else {
var str = '';
for (var i = 0; i < ret.length; i++) {
str += ret[i] + '<br>';
}
$('.box').html(str);
}
})
</script>
</body>
</html>