php +ajax +sql 實現資料互動

來源:互聯網
上載者:User
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'])."";}

    ------------------- 完畢 -----------------------


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.