jquery 表排序器 + ajax div内容更新问题

发布于 2024-07-16 22:41:08 字数 3270 浏览 6 评论 0原文

我的 tablesorter 和 ajax div 内容更新遇到问题。 一旦 ajax 重新加载,所有表排序器功能都会丢失。 我尝试过 livequery,但它似乎无法超出表的第一个列表。

<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);
} 

I'm having trouble with my tablesorter and ajax div content update. Once the ajax is reloaded all the tablesorter functionalities are lost. I've tried livequery but it doesn't seem to work beyond first listing of the table.

<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);
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

老子叫无熙 2024-07-23 22:41:08

您可以触发更新,而不是再次调用 .tablesorter(),而无需调用 .tablesorter() 的任何开销:

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

我已经在自己的项目中成功使用了它。 您可以在 :success 处理程序中进行 trigger() 调用。

华泰

Instead of calling .tablesorter() again, you can trigger an update instead, without any of the overhead of calling .tablesorter():

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

I've used this successfully in my own project. You can make the trigger() call in your :success handler.

HTH

べ繥欢鉨o。 2024-07-23 22:41:08

加载结果后,您需要再次执行 $("#table").tablesorter() 重新排序。 另外,不要手动编写 ajax 代码,而是使用 jquery 中的 $.get$.post

After loading the result, you need to do $("#table").tablesorter() once more to re-sort it. Also, rather than writing your ajax code by hand, use $.get or $.post from jquery

作死小能手 2024-07-23 22:41:08

您最初的问题是 Live Query 只能检测以 jQuery 调用开始的文档更改。

直接设置innerHTML不会导致它触发。 将该行更改为 $("#"+divid).html(xmlHttp_one.responseText) 就可以解决您的问题。

我很高兴听到您找到了解决方案! 但请注意,Live Query 必须在每次修改文档时扫描文档 - 这很方便,但会带来很大的性能损失。 最好将对 tablesorter() 的调用放在 jQuery.ajax(success:) 函数中。

Your original issue was that Live Query can only detect changes to the document that started with a jQuery call.

Directly setting innerHTML will not cause it to fire. Changing that line to $("#"+divid).html(xmlHttp_one.responseText) would have solved your problem.

I'm glad to hear that you found a solution! Be aware, however, that Live Query has to scan the document every time it is modified — which is convenient but comes with a big performance hit. It would be better to put the call to tablesorter() in your jQuery.ajax(success:) function.

用心笑 2024-07-23 22:41:08

我遇到了同样的问题并找到了这个方法。

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

它不是很漂亮,但是很有效!

I had the same problem and found this method.

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

It's not very pretty but it works!

我们只是彼此的过ke 2024-07-23 22:41:08

通过使用 jQuery .ajax 函数找到了解决方案。 更容易,并且工作完美。

Found a solution by using jQuery .ajax function. much easier, and works perfectly.

笑咖 2024-07-23 22:41:08

正如前面提到的,使用 jquery AJAX 调用是最好的方法 :P 但我发现这篇文章对于新手来说有点模糊,所以这是我在项目中使用的代码:

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

As mentioned using the jquery AJAX call is the best way to go :P but I found the post to be a bit vague for newbies so here's the code that i used in my project:

    $('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();
        }
    });
});
迷鸟归林 2024-07-23 22:41:08

使用ajaxStop函数,代码将在ajax调用完成后运行。

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

Use the ajaxStop function and the code will run after the ajax call is complete.

$("#DivBeingUpdated").ajaxStop(function(){ 
    $("table").tablesorter()
});
記柔刀 2024-07-23 22:41:08

我对 java/ajax 编程很陌生,但有完全相同的问题 - 当我用我的表更新 div 的内容(使用 ajax)时,tablesorter 不起作用。 如果我将表格直接加载到第一页(而不是 div 中),则 tablesorter 可以完美工作。

因此,如果您能更详细地解释您是如何修改代码来解决这个问题的,我将不胜感激。

谢谢,博扬

I am quite new in java/ajax programming, but have exactly the same problem - when I update the content of a div (using ajax) with my table, tablesorter does not function. If I load the table directly to the very first page (not into a div), tablesorter works perfectly.

So, I would be greatful if you can explain in more details how exactly you modified your code to solve it.

Thanks, Bojan

执着的年纪 2024-07-23 22:41:08

答案与所提出的问题无关,但可能对某人有帮助。

如果通过 AJAX 调用加载表内容,则必须在成功执行 AJAX 调用后调用 tablesorter() 函数。
解释相同的代码 -->

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

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>

The answer is irrelevant to the question asked but it might help someone.

In case of loading table contents via AJAX call the function tablesorter() must be called after successful execution of AJAX call.
Code that explains the same -->

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

The contents of nutrition.xml file :

<?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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文