[英]Jquery:Remove DOM element after ajax success
I am having trouble trying to remove an element after an ajax success.. 在ajax成功之后,我无法尝试删除元素。
here is my ajax code: 这是我的ajax代码:
verifyRequest.denyUser = function(requestId,element){
$.ajax({
url: loaderURL+'idverified/denyRequest',
dataType:"json",
type:"post",
data:{
id:requestId,
},
success: function(data){
element.remove();
}
});
}
And listening to this event: 并听取此事件:
$("#requestUsers ul li .remove").click(function(){
var id = $(this).attr("data-value"),
element = $(this).parent('li');
verifyRequest.denyUser(id,element);
});
The problem is this - The ajax is working fine however when it comes to the "success:" part it does not remove the element. 问题是这个 - ajax工作正常但是当涉及到“成功:”部分它不会删除元素。
I tried this code and it worked however this does not suit my needs : 我尝试了这个代码但是它有效但是这不符合我的需要:
$("#requestUsers ul li .remove").click(function(){
var id = $(this).attr("data-value"),
element = $(this).parent('li');
verifyRequest.denyUser(id,element);
element.remove();//and it did worked
});
can somebody explain why is this happening?Thanks 有人可以解释为什么会这样吗?谢谢
store the reference and then remove it.this way: 存储引用然后将其删除。这样:
verifyRequest.denyUser = function(requestId,element){
var t = $(element);
$.ajax({
url: loaderURL+'idverified/denyRequest',
dataType:"json",
type:"post",
data:{
id:requestId,
},
success: function(data){
$(t).remove();
}
});
}
SOLUTION: The problem is actually on server side .. If you are depending on success event your server side must always return a json.. even if its empty or what ever you prefer. 解决方案:问题实际上是在服务器端。如果你依赖于成功事件,你的服务器端必须总是返回一个json ..即使它是空的或你喜欢什么。 Because success will be triggered only if
因为只有在成功时才会触发成功
<?php
if(isset($_POST['yourData']) && !empty($_POST['yourData'])){
if(//evaluate further){
// This will trigger success
echo json_encode(array());
}else{
throw new HttpException(403,'Unauthorized request');
}
}else{
throw new HttpException(404,'Not Found')
}
?>
This way success will be triggered if your evaluation returns true.. 这样,如果您的评估返回true,将触发成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.