web开发之-练习(记事本功能)

今天我们做一个小玩意,就是一个简单的记事本功能,这里会用到我们之前学到的基本知识的整合,让大家对web软件有一个更深层次的认识。

功能流程如下:

界面有一个文本输入框,一个姓名输入框(模拟不同的人),提交到后台经由php进行处理,并保存到数据库中,界面进行刷新会获取到插入的数据。

我们之前的web数据库中,创建一个notebook数据表,保存用户信息留言内容:

create table notebook (id int not null primary key auto_increment,username varchar(10) comment “用户名”,content text comment “记事本内容”);

notebook.html

js 留言列表: 提交

notebook.js

$(“.ajax_btn”).click(function(){ var username = $(“.note_username”).val(); var content = $(“.note_content”).val(); var xhr = new XMLHttpRequest(); xhr.open(“post”,”http://localhost/notebook.php”,true); xhr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4 && xhr.status == 200) { window.location.reload(true); } } var str = “username=”+username; str += “&content=”+content; xhr.send(“act=addInfo&”+str); }); // 获取留言列表 var xhr = new XMLHttpRequest(); xhr.open(“post”,”http://localhost/notebook.php”,true); xhr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”); xhr.onreadystatechange = function(e) { if(xhr.readyState == 4 && xhr.status == 200) { var list = JSON.parse(xhr.responseText); var listStr = “”; for(var i=0;i<list.length;i++) { var info = list[i]; listStr +=""+info.username+"说: "+info.content+"" } $(".note_list").html(listStr); } } xhr.send("act=allInfo");})

注:我们使用jqeury在这个html加载进来的时候,会向后台发起请求获取已留言的用户信息!当我们点击提交按钮的时候,会把输入的留言内容和模拟的留言用户发送到后台notebook.php文件,收到返回信息后重新刷界面获取最新的列表,你也可以通过更改后台逻辑使用jquery来动态添加数据。

notebook.php

conn = new mysqli($this->hostname,$this->username,$this->password); if($this->conn->connect_error) { trigger_error(“连接失败”); } } public function allInfo($database,$table) { $this->conn->query(“use “.$database); $data = $this->conn->query(“select * from “.$table); $result = $data->fetch_all(MYSQLI_ASSOC); return $result; } public function addInfo($database,$table,$data) { $this->conn->query(“use “.$database); $sql = “insert into “.$table.”(“; $keyStr = “”; $valueStr = “”; foreach($data as $k=>$v) { $keyStr.=$k.”,”; $valueStr.=”‘$v'”.”,”; } $keyStr = substr($keyStr,0,strlen($keyStr)-1); $valueStr = substr($valueStr,0,strlen($valueStr)-1); $sql.=$keyStr.”) values (“.$valueStr.”)”; $state = $this->conn->query($sql); return $sql; }}$mysql = new MySql();$result = “”;switch($_POST[“act”]){ case “addInfo”: $info = array(“username”=>$_POST[“username”],”content”=>$_POST[“content”]); $result = $mysql->addInfo(“web”,”notebook”,$info); break; case “allInfo”: $result = $mysql->allInfo(“web”,”notebook”); break;}print_r(json_encode($result));

注:

在这里我们封装了一个自定义的MySql类,这个类里有两个方法,通过发送过来的act参数判断用户的操作,allInfo 是获取留言列表,addInfo是用来添加留言,通过MySql提供的两个方法来调用插入数据和获取数据。

注:我们写完上面这些代码后,通过在址址栏里输入localhost/notebook.html,这里访问的是html文件,而不是那个php文件。

郑重声明:本文内容及图片均整理自互联网,不代表本站立场,版权归原作者所有,如有侵权请联系管理员(admin#wlmqw.com)删除。
(0)
用户投稿
上一篇 2022年6月28日
下一篇 2022年6月28日

相关推荐

联系我们

联系邮箱:admin#wlmqw.com
工作时间:周一至周五,10:30-18:30,节假日休息