日期:2014-05-16  浏览次数:20644 次

利用MVC和Ajax实现->鼠标移动到热点上,显示详细信息

userController.class.php

public function showDetailAction(){
  //处理的是详细信息
  $userModel = new userModel('localhost','xuefei','root','123');
  $row = $userModel->searchAll();
  $this->smarty->assign('list',$row);
  $this->smarty->display('showDetail.tpl');
  }
 public function processAction(){
  $user_id = $_REQUEST['user_id'];
  $userModel = new userModel('localhost','xuefei','root','123');
  $row = $userModel->getOne($user_id);
  //var_dump($row);
  //echo $row['stu_id'];
  //json格式发送集合类的数据 json_encode()可以将数组转化成json格式的字符串
  echo json_encode($row);//因为现在数据库返回的是一条记录(数组)
  }

userModel.class.php

public function searchAll(){
  $sql = "select*from qf";
  $result = mysql_query($sql);
  $rows = array();
  while($row = mysql_fetch_assoc($result)){
   $rows[] = $row;
   }
  return $rows; 
  }
 public function getOne($user_id){
  $sql = "select * from qf where stu_id ='".$user_id."'";
  $result = mysql_query($sql);
  //file_put_contents('d://test.txt',$sql,FILE_APPEND);
  $row = mysql_fetch_assoc($result);
  return $row;
  } 

showDetail.tpl

<table align="center"  bgcolor="#99CCCC" border="1">
<tr><th>显示详细信息</th></tr>
<{foreach from=$list item="value"}>
<tr style="background-color:#ccc">
<td id="name_<{$value.stu_id}>"><{$value.stu_id}></td>
<td onmouseover="showDetail(<{$value.stu_id}>)"  onmouseout="hideDetail(<{$value.stu_id}>)">
    <{$value.stu_name}></td>
</tr>
<{/foreach}>
</table>
<script>
function showDetail(user_id){
 var xhr;     //理解成打开浏览器
   if(window.ActiveXObject){  //这是IE浏览器的
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }else if(window.XMLHttpRequest){  //这里是火狐浏览器的
    xhr = new XMLHttpRequest();
   }
   xhr.open("POST","index.php?c=user&a=process",true);        //打开地址栏
   xhr.onreadystatechange = callback;   //监视请求的状态的
   xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   xhr.send('user_id='+user_id);
   function callback(){
    if(xhr.readyState ==4){   //表示请求已经完成
     if(xhr.status==200)
     {
     //alert(typeof(xhr.responseText));
     //但是需要注意:eval()如果想要字符串转化成对象,需要先将字符串运行一下,通过()
     var json = eval('('+xhr.responseText+')');
     var new_div = document.createElement('div');
     new_div.style.backgroundColor = "#ccc";
     new_div.style.position = "absolute";
     new_div.id = "new_div"+user_id;
     new_div.style.marginLeft = '170px';
     new_div.innerHTML = "id:"+json.stu_id+"<br/>username:"+json.st