如果用ajax来操作的话每次成功和失败的提示会比TP的好狠多。


在写程序的时候碰到一个删除用户的问题,因为自己JS比较差的,这次就想用JS来处理。这里的话之前的代码就不贴了。
首先是控制器代码:
public function userList(){
$this->assign("user","active open");
$this->assign("userlist","class='active'");
$User= M('User');
$count= $User->count();
$this->assign("num",$count);
$Page= new \Think\Page($count,10);
$show= $Page->show();
$list= $User->order('u_time')->limit($Page->firstRow.','.$Page->listRows)->select();
$this->assign('list',$list);
$this->assign('page',$show);
$this->display();
}然后对应的视图代码:
<div class="widget-content">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th width="5%">用户编号</th>
<th width="15%">登陆用户名</th>
<thwidth="15%">权限组</th>
<th width="20%">联系邮箱</th>
<th width="20%">添加时间</th>
<th width="20%">操作</th>
</tr>
</thead>
<tbody>
<volist name="list" id="k">
<tr>
<td class="id">{$k.u_id}</td>
<td>{$k.u_name}</td>
<td>
<switch name="k['u_class']">
<case value="1">最高管理员</case>
<case value="2">普通管理员</case>
<default />普通用户
</switch>
</td>
<td>{$k.u_email}</td>
<td>{$k.u_time}</td>
<td>
<button class="btn btn-success btn-sm"><a href="{:U('/Admin/User/userEdit',array('id'=>$k['u_id']))}">编辑</a></button>
<button class="btn btn-danger btn-sm deluser">删除</button>
</td>
</tr>
</volist>
</tbody>
</table>
{$page}
</div>然后展现出来的效果是:

当我点击编辑的时候a链接可以带id去访问userEdit控制器,去查询用户数据然后展现出来。删除的话,我之前的写法是
onClick="return confirm('是否删除这篇文章')"然后补上 a 链接到 userDel 这样的话系统默认的弹出框感觉和程序的风格不搭,但是如果需要用到ajax来发送的话怎么获取数据呢?
在网上百度之后是先获取父元素然后再搜索子元素。
<script>
$(document).ready(function(){
$(".deluser",this).click(function(){
var id = $(this).parents("tr").find(".id").text();
console.log(id);
});
});
</script>这里因为我测试的时候给予 删除这个按钮 id的话会出现只能点击一次的效果,所以我换成class来测试的。先获取 deluser 这个元素的父元素 parents("tr")获取的是这一行的父元素,然后去查询这一行的第一个用户编号,这里我给了一个class="id" 来方便获取值
然后用find(".id")来查询到这个class,再用text()来获取值,这时候就可以发送ajax来处理数据了。

上一篇: 给文章加上代码高亮...
下一篇: HTML转义和反转义...