JQuery - removing table rows after AJAX call
I am trying to refresh a page after an AJAX method call (admitedly, this rather defeats the purpose of the AJAX method) - but I am coming up against a hard deadline, and I need to complete development, and I am fairly new at using jQuery.
I have a table that displays checkboxes on the left had side. A user can开发者_开发问答 select one or more check boxes, and then click on an image, which fires of an AJAX call. After the call returns, I want to remove the selected rows from the displayed table (effectively truncating the table).
I have managed to write code to do the first bit (firing the AJAX code for the selected rows), but I am a bit
jQuery('#id1').click(function(){
var selected = new Array();
jQuery('#Cntnr').find('table input:checkbox:checked').each(function(){
selected.push(jQuery(this).attr("id"));
});
if (selected.length > 0) {
if (confirm('Blah, blah ..?')) {
jQuery.post("example.com", { ids: selected.join(';') },
function(data){
jQuery(data.id).html(data.payload);
alert('unreachable code ?!');
}, "json");
}
}else alert('select a checkbox first.');
});
I have placed an alert() function as part of the callback - this is where I expect statements to remove the rows will be placed - however, the line appears to be unreachable, as the alert box is never displayed.
I would be grateful if someone can edit the above code, so that the selected rows will be removed from the table as part of the callback. the elements have id attributes which match those in the selected variable.
Firstly, are you currently posting the data to "example.com"?
If so, there will be error on this line:
jQuery(data.id).html(data.payload);
as data.payload
is not defined. Thus the code will not continue.
Also if you're expecting JSON return type, use jQuery.postJSON()
instead of jQuery.post()
.
As for removing the roles, you will need the server to return you the list of IDs that are removed, and loop through each row to find the IDs which are removed and remove the rows.
Example:
Array.prototype.has=function(v){
for (i=0;i<this.length;i++){
if (this[i]==v) return true;
}
return false;
}
var arr = data.ids.split(';');
jQuery('#Cntnr').find('table tr input:checkbox').each(function(){
var $this = $(this);
if(arr.has($this.attr('id'))){
$this.parent('tr').remove();
}
});
精彩评论