php +ajax +sql 实现数据交互

来源:互联网 发布:我的世界服务器开挂js 编辑:程序博客网 时间:2024/05/18 00:26

1.首先新建个sql表,表内容如上所示:


2.新建个公用文件conn.php来链接数据库:

<?phpheader("Content-Type:text/html;charset=utf8");//申明编码格式$conn=mysql_connect("localhost","root","aaaaaa") or die("数据库连接错误".mysql_errno());//连接sqlmysql_select_db("phptest",$conn);mysql_query('SET NAMES UTF8') or die('字符集设置错误'.mysql_error());//设置输入的字符集编码?>
3.php服务端提供给前端ajax数据接口,新建文件phptoAJAX。php
<?phprequire_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方法,执行后的页面如下图所示:
<!DOCTYPE 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;i<msg.length-1;i++)//这里是限定10    
            {   
                li+="<li><h2>"+msg[i]['title']+"</h2><p>"+msg[i]['content']+"...<a href='phpArtcle.php?art="+msg[i]['id']+"' target='_blank'>详细</a></p></li>";                                   }   
             $("#list").html(li);     
      },   
         error:function()//如果接收不成功执行以下
            {                    console.log("链接错误")            }        });    });</script></body></html>
5.点击上一步图中所示的“详细”链接,可查看对应的文章内容,新建phpArtcle.php文件
<?phprequire_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 "<h1>".$rows['title']."</h1>"; echo "<div>".htmlspecialchars_decode($rows['content'])."</div>";}
-------------------完毕-----------------------



2 0