Domanda

Ho problemi con il mio aggiornamento dei contenuti tablesorter e Ajax div. Una volta che l'Ajax è ricaricato tutte le funzionalità tablesorter sono persi. Ho provato livequery ma non sembra funzionare al di là di primo elenco della tabella.

<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);
} 
È stato utile?

Soluzione

Dopo aver caricato il risultato, è necessario fare $("#table").tablesorter() una volta di più per riordinare esso. Inoltre, piuttosto che scrivere il codice Ajax a mano, utilizzare $.get o $.post da jquery

Altri suggerimenti

Invece di chiamare .tablesorter () ancora una volta, è possibile attivare un aggiornamento, invece, senza che nessuna delle spese generali di chiamare .tablesorter ():

("#table").trigger("update");

Ho usato questo successo nel mio progetto. È possibile effettuare la chiamata di innesco () nel:. Handler successo

HTH

Il problema originale era che dal vivo query può rilevare solo modifiche al documento che è iniziato con una chiamata jQuery.

Direttamente impostazione innerHTML non lo farà al fuoco. Cambiare questa linea di $("#"+divid).html(xmlHttp_one.responseText) avrebbe risolto il problema.

Sono contento di sentire che hai trovato una soluzione! Essere consapevoli, tuttavia, che dal vivo ha Query per eseguire la scansione del documento ogni volta che viene modificata - che è conveniente, ma è dotato di un grande calo di prestazioni. Sarebbe meglio mettere la chiamata a tablesorter() nella funzione jQuery.ajax(success:).

Ho avuto lo stesso problema e ho trovato questo metodo.

$("#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");

Non è molto bello, ma funziona!

trovato una soluzione utilizzando la funzione jQuery Ajax. molto più facile, e funziona perfettamente.

Come accennato utilizzando la chiamata AJAX jQuery è il modo migliore per andare: P ma ho trovato il posto per essere un po 'vago per i neofiti ecco il codice che ho usato nel mio progetto:

    $('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();
        }
    });
});

Utilizzare la funzione ajaxStop e il codice verrà eseguito dopo la chiamata AJAX è completa.

$("#DivBeingUpdated").ajaxStop(function(){ 
    $("table").tablesorter()
});

Sono abbastanza nuovo nella programmazione java / ajax, ma hanno esattamente lo stesso problema - quando aggiorno il contenuto di un div (utilizzando Ajax) con il mio tavolo, tablesorter non funziona. Se io caricare la tabella direttamente alla prima pagina (non in un div), tablesorter funziona perfettamente.

Quindi, sarei grato se si può spiegare più in dettaglio come esattamente hai modificato il codice per risolverlo.

Grazie, Bojan

La risposta è irrilevante per la questione ha chiesto ma potrebbe aiutare qualcuno.

Nel caso di contenuti della tabella di carico tramite AJAX chiamare la funzione tablesorter () deve essere chiamato dopo l'esecuzione riuscita di AJAX chiamata. Il codice che spiega lo stesso ->

        $(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.");
        });         
    });

Il contenuto del file 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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top