主页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="./jquery.js"></script><style>*{font-size: 16px;margin: 0;padding: 0;}.wrapper{width: 800px;height: 550px;margin: 0 auto;display: flex;flex-direction: column;justify-content: center;align-items: center;}.contents{width: 800px;height: 500px;padding: 10px;overflow: auto;border: 1px solid black;}.contents p{display: flex;align-items:center;margin-top: 10px;padding: 10px;border-radius: 25px;background-color: skyblue;}.contents p span{margin: 0 20px;}input[type=text]{width: 250px;height: 35px;margin-top: 10px;}input[type = button]{width: 40px;height: 35px;margin-top: 10px;}</style>
</head>
<body><div class="wrapper"><div class="contents"></div><div><input type="text" name="content" id="content" placeholder="请输入你的留言"><input type="button" id="send" value="发送"></div></div><script>function getInfo(){$.ajax({"url":"./action.php","method":"post","dataType":"json","data":{query:"ok"},success(res){$(".contents").empty();for(var i = 0; i<res.length; i++){str = `<p><span>第${res[i].id}楼</span>留言:${res[i].content}--时间:${res[i].time}</p>`;$(".contents").append(`${str}`);}}})}$(document).ready(function(){getInfo();})$("#send").click(function(){var content = $("#content").val();$.ajax({"url":"./action.php","method":"post","dataType":"json","data":{query:"add",content:content},success(res){console.log(res);if(res.state = "addSuccess"){getInfo();}}})$("#content").val('');})$(document).keyup(function(e){if(e.keyCode == 13){$("#send").click();}})</script>
</body>
</html>
把index页面的数据发送到action页面,在action页面进行处理
<?
include("./mysql.php");// 查询数据
function query(){$arr = select();return json_encode($arr);
}
if($_POST["query"] == "ok"){echo query();
}// 添加数据function query2(){$content = $_POST["content"];// var_dump($content);$res2 = add($content);if($res2){echo json_encode(['state'=>'addSuccess']);}
}
if($_POST["query"] == "add"){query2();
}
?>
action需要在mysql引入函数
<?
$host = "localhost";
$dbuser = "root";
$dbpwd = "root";
$dbname = "scb";$con = mysqli_connect($host,$dbuser,$dbpwd,$dbname);if (!$con) {die ('数据库停止运行');
}// 查询数据
function select(){global $con;$sql = "select * from `1999`";$res = mysqli_query($con,$sql);$arr = [];if($res){while($row = mysqli_fetch_assoc($res)){$arr[] = $row;}}return $arr;
}// 添加数据
function add($content){global $con;$time = time();$time = date('Y-m-d h:i:s',$time);$sql = "insert into `1999`(content,time) values('$content','$time');";$res = mysqli_query($con,$sql);return $res;
}
?>
经过处理,把数据库的数据发送到index页面,在index页面显示出来,也可以在index页面进行数据的添加
结果展示: