今天我們做一個(gè)小玩意,就是一個(gè)簡(jiǎn)單的記事本功能,這里會(huì)用到我們之前學(xué)到的基本知識(shí)的整合,讓大家對(duì)web軟件有一個(gè)更深層次的認(rèn)識(shí)。
功能流程如下:
界面有一個(gè)文本輸入框,一個(gè)姓名輸入框(模擬不同的人),提交到后臺(tái)經(jīng)由php進(jìn)行處理,并保存到數(shù)據(jù)庫中,界面進(jìn)行刷新會(huì)獲取到插入的數(shù)據(jù)。
我們之前的web數(shù)據(jù)庫中,創(chuàng)建一個(gè)notebook數(shù)據(jù)表,保存用戶信息和留言內(nèi)容:
create table notebook (id int not null primary key auto_increment,username varchar(10) comment “用戶名”,content text comment “記事本內(nèi)容”);
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在這個(gè)html加載進(jìn)來的時(shí)候,會(huì)向后臺(tái)發(fā)起請(qǐng)求獲取已留言的用戶信息!當(dāng)我們點(diǎn)擊提交按鈕的時(shí)候,會(huì)把輸入的留言內(nèi)容和模擬的留言用戶發(fā)送到后臺(tái)notebook.php文件,收到返回信息后重新刷界面獲取最新的列表,你也可以通過更改后臺(tái)邏輯使用jquery來動(dòng)態(tài)添加數(shù)據(jù)。
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));
注:
在這里我們封裝了一個(gè)自定義的MySql類,這個(gè)類里有兩個(gè)方法,通過發(fā)送過來的act參數(shù)判斷用戶的操作,allInfo 是獲取留言列表,addInfo是用來添加留言,通過MySql提供的兩個(gè)方法來調(diào)用插入數(shù)據(jù)和獲取數(shù)據(jù)。
注:我們寫完上面這些代碼后,通過在址址欄里輸入localhost/notebook.html,這里訪問的是html文件,而不是那個(gè)php文件。