[英]delete row in jquery without page refresh
我正在使用此代码删除一行..我的代码工作正常,我在使用数据表,其中每行前面都有一个按钮删除..当确认对话框出现时,我想要的是什么,用户按确定,然后它删除该行并显示数据库中的剩余行而无需刷新..我的意思是当时如果我按ok按钮,它将成功删除该行..但是删除行会保留在表中,直到我刷新页面,然后它从表中删除..那有可能吗?..因为我不希望用户按删除后他必须刷新以查看该行是否被删除..
这是我的查看代码用户名
<td> <a href = "employesController/deleteEmploye/<?php echo $row->emp_id ?>"
class = "deletes" >Delete</td>
我的jQuery代码
<script type='text/javascript'>
$(document).ready(function(){
$(".deletes").click(function(e){
var r = confirm("are you sure you want to delete this");
if (r==true){
$this = $(this);
e.preventDefault();
var url = $(this).attr("href");
$.get(url, function(r){
if(r.success){
$this.closest("tr").remove();
}
})
}else {
return false;
}
});
});
我的控制器
function deleteEmploye($empid){
$id = $empid;
$this->load->model('employesModel');
$query = $this->employesModel->deleteEmploye($id);
return json_encode(array("success" => true));
模型
public function deleteEmploye($id){
$this->db->where('emp_id', $id);
$query = $this->db->delete('employees');
return $query->result();
}
使用Firebug(如果不使用firefox,则使用类似的工具)来调试ajax调用。 在“网络”选项卡中,您可以查看您的ajaxrequest是否确实已发送,以及返回的内容。
将console.log和console.dir语句添加到您的代码中,以了解发生了什么:
$.get(url, function(r){
console.log("returned form ajax");
if(r.success){
console.log("successful, $this is now ");
console.dir($this);
$this.closest("tr").remove();
}
}
这样,您将发现ajax确实会返回,但不会返回您期望的结果:它只会返回数据,因此查找r.success总是会失败。
您正在使用的.get方法仅接受两个参数:url和仅在成功的情况下才调用的函数! 因此,您根本不需要if语句:
$.get(url, function(r){
$this.closest("tr").remove();
}
有关完整的示例,请参见http://jsfiddle.net/bjelline/8RQQN/ 。
另外:不使用获取删除内容! 请改用帖子 ! 您还应该考虑跨站点请求伪造:完全不同站点上的某人可能会添加一个链接
<a href="http://yoursite.com/employesController/deleteEmploye/4">free beer here</a>
欺骗您的用户删除雇员-甚至没有引起注意!
参见https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
您可以使用jquery发送到php中的另一个脚本来删除该行,并且可以确认您可以删除表的这一行
jQuery的
$.post("functions.php", { rowId: 1231 },
function(data) {
if (data == "ok")
alert("the row has ben delete");
else
alert("the row is not delete");
});
的PHP
<?php
function delete_row(){
//action to delete row in db
// when the row has bes delete you can print ok
echo 'ok';
//if you have a error you can print a message that you can managed y jquery
echo "error 2121123"
}
if(isset($_post["rowId"]))
delete_row($_post["rowId"]);
首先,您需要验证是否调用了if条件块。 如果调用正确,请尝试以下一种方法:
$this.parent('td').parent('tr').remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.