jquery tablesorter + ajax div problema de atualização de conteúdo
-
23-08-2019 - |
Pergunta
Estou tendo problemas com meu tablesorter e atualização de conteúdo div ajax. Uma vez que o ajax é recarregado todas as funcionalidades Tablesorter são perdidas. Eu tentei livequery mas não parece trabalho para além primeira listagem da tabela.
<script type="text/javascript">
$(document).ready(function(){
$(".tabs > ul").tabs();
$("#sortabletable").tablesorter({
headers: {
4: { sorter: false },
5: { sorter: false }
},
widgets:['zebra'],
sortlist:[[0]]
});
});
$("#sortabletable").livequery(function(){
$(this).tablesorter({
headers: {
4: { sorter: false },
5: { sorter: false }
},
widgets:['zebra'],
sortlist:[[0]]
});
});
</script>
// The AJAX function...
function AJAX(){
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
}
// Timestamp for preventing IE caching the GET request (common function)
function fetch_unix_timestamp(){
return parseInt(new Date().getTime().toString().substring(0, 10))
}
////////////////////////////////
//
// Refreshing the DIV TIMEDIV
//
////////////////////////////////
function events_listings(){
// Customise those settings
var seconds = 5;
var divid = "tab01";
var url = "events_listings.php";
// Create xmlHttp
var xmlHttp_one = AJAX();
// No cache
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp_one.onreadystatechange=function(){
if(xmlHttp_one.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
setTimeout('events_listings()',seconds*1000);
}
}
xmlHttp_one.open("GET",nocacheurl,true);
xmlHttp_one.send(null);
}
// Start the refreshing process
window.onload = function startrefresh(){
setTimeout('events_listings()',seconds*1000);
}
////////////////////////////////
//
// Refreshing the DIV TIMEINWASHINGTON
//
////////////////////////////////
var formvar = "";
function view_job(temp){
// Customise those settings
var seconds = 8;
var divid = "tab02";
var url = "view_job.php";
formvar = temp;
// Create xmlHttp
var xmlHttp_two = AJAX();
// No cache
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp+"&"+formvar;
// The code...
xmlHttp_two.onreadystatechange=function(){
if(xmlHttp_two.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp_two.responseText;
setTimeout('view_job(formvar)',seconds*1000);
}
}
xmlHttp_two.open("GET",nocacheurl,true);
xmlHttp_two.send(null);
}
// Start the refreshing process
window.onload = function startrefresh(){
setTimeout('view_job(formvar)',seconds*1000);
}
Solução
Depois de carregar o resultado, você precisa fazer $("#table").tablesorter()
mais uma vez para re-classificá-lo. Além disso, ao invés de escrever seu código ajax à mão, $.get
uso ou $.post
do jQuery
Outras dicas
Em vez de chamar .tablesorter () novamente, você pode acionar uma atualização em vez disso, sem qualquer da sobrecarga de chamar .tablesorter ():
("#table").trigger("update");
Eu usei isso com sucesso no meu próprio projeto. Você pode fazer a chamada trigger () na sua:. Manipulador de sucesso
HTH
A sua emissão original era que o Live consulta só pode detectar alterações no documento, que começou com uma chamada jQuery.
directamente à definição do innerHTML não fará com que ele fogo. Alterar essa linha para $("#"+divid).html(xmlHttp_one.responseText)
teria resolvido o problema.
Estou feliz em saber que você encontrou uma solução! Esteja ciente, no entanto, que o Live consulta tem para digitalizar o documento cada vez que é modificado - que é conveniente, mas vem com um grande impacto na performance. Seria melhor para colocar a chamada para tablesorter()
em sua função jQuery.ajax(success:)
.
Eu tive o mesmo problema e encontrou este método.
$("#table tbody tr").addClass("to-delete");
$("#table tbody").append(data);
$("#table").trigger("update");
$("#table").trigger("appendCache");
$("#table").trigger("sorton",[[[2,1],[0,0]]]);
$("#table tbody tr.to-delete").remove();
$("#table").trigger("update");
Não é muito bonito, mas funciona!
Encontrado uma solução usando função jQuery .ajax. muito mais fácil, e funciona perfeitamente.
Como mencionado usando a chamada de AJAX jQuery é o melhor caminho a percorrer: P mas eu achei o cargo para ser um pouco vago para iniciantes então aqui está o código que eu usei no meu projeto:
$('input.user').click(function() {
var getContact = $(this).val();
$.ajax({
url: 'contact_table.php',
data: 'userID='+getContacts,
success: function(result) {
$('#UserContactTable').append(result);
$("#contact-list").tablesorter();
}
});
});
Use a função ajaxStop eo código será executado após a chamada ajax está completa.
$("#DivBeingUpdated").ajaxStop(function(){
$("table").tablesorter()
});
Eu sou muito novo em java / ajax programação, mas têm exatamente o mesmo problema - quando eu atualizar o conteúdo de uma div (usando ajax) com minha mesa, tablesorter não funciona. Se eu carregar a tabela diretamente para a primeira página (não em um div), tablesorter funciona perfeitamente.
Então, eu ficaria grato se você pode explicar com mais detalhes como exatamente você modificou seu código para resolvê-lo.
Obrigado, Bojan
A resposta é irrelevante para a pergunta, mas pode ajudar alguém.
Em caso de conteúdo da tabela de carregamento via AJAX chamar a função tablesorter () deve ser chamado após a execução bem sucedida de chamada AJAX. Código que explica o mesmo ->
$(document).ready(function(){
//once the document is loaded make the AJAX call to required url
$.ajax({
url : 'nutrition.xml', //I have accessed nutrition.xml file
type : 'GET',
dataType : 'xml' //return type is xml
})
.done(function(xml){
//after successful call
/*here i have created an html string but,
one call also use appendTo() like :
$("<thead></thead>").appendTo("table"); and so on.. */
var str = "<thead><tr><th>Name</th><th>Calories</th></tr></thead><tbody>";
//loop through each element of xml filer
$(xml).find('food').each(function(i){
var name = $(this).find('name').text();
var calories = $(this).find('calories').attr('total');
//append to string
str = str + "<tr><td>"+name+"</td><td>"+calories+"</td></tr>";
});
str = str + "</tbody>";
//set html for <table>
$("table").html(str);
//the main part call tablesorter() once contents are set successfully
$("table").tablesorter({debug: true});
})
.fail(function(xhr,status,errorThrown){
//on ajax call failure
alert("An error occurred while processing XML file.");
});
});
O conteúdo do arquivo nutrition.xml:
<?xml version="1.0"?>
<nutrition>
<food>
<name>Avocado Dip</name>
<calories total="110" fat="100"/>
</food>
<food>
<name>Bagels, New York Style </name>
<calories total="300" fat="35"/>
</food>
<food>
<name>Beef Frankfurter, Quarter Pound </name>
<calories total="370" fat="290"/>
</food>
</nutrition>