1.首先建立個sql表,表內容如上所示:
2.建立個公用檔案conn.php來連結資料庫:
header("Content-Type:text/html;charset=utf8");//申明編碼格式 $conn=mysql_connect("localhost","root","aaaaaa") or die("資料庫連接錯誤".mysql_errno());//串連sql mysql_select_db("phptest",$conn); mysql_query('SET NAMES UTF8') or die('字元集設定錯誤'.mysql_error());//設定輸入的字元集編碼 ?>
3.php服務端提供給前端ajax資料介面,建立檔案phptoAJAX。php
require_once("conn.php");//匯入公用檔案 $query=mysql_query("SElECT * FROM txt") or die("錯誤提示:".mysql_error()); $jsonArray=array();//建立資料用於接收資料庫每行對應的資料群組 while($rows=mysql_fetch_array($query)) { //處理資料庫裡面的自動對應的內容 $rows['content']=mb_substr(strip_tags(htmlspecialchars_decode($rows['content'])),0,100,"utf-8"); //把資料庫的內容添加到建立數組中
array_push($jsonArray,$rows);//注意這裡是$rows } echo json_encode($jsonArray);//轉換成json傳遞給前端
4.建立phpToAJAX.HTML前端接收資料,這裡我用jquery封裝好的ajax方法,執行後的頁面如所示:
html><html><head lang="en"> <meta charset="UTF-8"> <title>title> <script type="text/javascript" src="jquery-1.8.3.min.js">script>head><body><ul id="list">
ul><script type="text/javascript"> $(function(){ $.ajax({ type: "post",//傳遞方法 url: "phpToAJAX.php",//資料介面 dataType: "json",//接收格式 success: function(msg)//如果接收成功執行以下 { var li=""; for(var i =0;ilength-1;i++)//這裡是限定10個 { li+="
"+msg[i]['title']+"
"+msg[i]['content']+"...+msg[i]['id']+"' target='_blank'>詳細
"; } $("#list").html(li); }, error:function()//如果接收不成功執行以下 { console.log("連結錯誤") } }); });script>body>html>5.點擊上一步圖中所示的“詳細”連結,可查看對應的文章內容,建立phpArtcle.php檔案
require_once("conn.php"); $id=$_GET['art'];//接收前端上傳的資料//查詢資料庫對應的內容
$query=mysql_query("SELECT * FROM txt WHERE id='$id'") or die("文章錯誤:".mysql_error());//遍曆數組,顯示內容
if($rows=mysql_fetch_array($query)){ echo "".$rows['title']."
"; echo "".htmlspecialchars_decode($rows['content'])."";}
------------------- 完畢 -----------------------