鼠标移动到热点上,显示详细信息(显示数据库的信息)
这也是在mvc中做的一个小实例(以表格的形式输出数据库的内容 在鼠标移到区域上会显示详细的关于这个的信息以div的形式在右边显示)
showDetail.tpl文件源码
<table align="center" >
<tr>
<th>显示详细信息</th>
</tr>
<{foreach from=$list item="value"}>
<tr style="background-color:#ccc">
<td id="name_<{$value.id}>"><{$value.id}></td>
<td onmouseover="showDetail(<{$value.id}>)" onmouseout="hideDetail(dd)"><{$value.username}></td>
</tr>
<{/foreach}>
</table>
<script>
function showDetail(id){
var xhr;
if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
//换一种形式发送ajax请求post
xhr.open("POST","index.php?c=user&a=process",true);
xhr.onreadystatechange = callback;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send('id='+id);
function callback(){
if(xhr.readyState ==4){
if(xhr.status==200){
//alert(xhr.responseText);
var json = eval('('+xhr.responseText+')');
var new_div = document.createElement('div');
new_div.style.backgroundColor="#ccc";
new_div.innerHTML="id:"+json.id+"<br/>username:"+json.username+"<br/>password:"+json.password;
new_div.style.position='absolute';
new_div.style.marginLeft='70px';
new_div.id="new_div"+id;
document.getElementById('name_'+id).appendChild(new_div);
}
}
}
}
function hideDetail(id){
var new_div=document.getElementById("new_div"+id);
document.getElementById("new_div"+id).removeChild(new_div);
}
</script>
Controller控制器
userController.class.php文件中代码
public function showDetailAction(){
//处理的是详细信息
$userModel = new userModel('localhost','root','123','ajax');
$rows = $userModel ->searchAll();
$this ->smarty->assign('list',$rows);
$this ->smarty ->display("showDetail.tpl");
}
public function processAction(){
$id = $_REQUEST['id'];
$userModel = new userModel('localhost','root','123','ajax');
$row = $userModel ->getOne($id);
//json格式发送集合类的数据 json_encode()可以将数组转化成json格式的字符串
echo json_encode($row);//因为现在数据库返回的是一条记录(数组)
}
model模型
userModel.class.php
public function searchAll(){
$sql = "select * from user";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
return $rows;
}
public function getOne($id){
$sql = "select * from user where id=".$id;
//file_put_contents("d://te.txt",$user_id,FILE_APPEND);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;}