簡體   English   中英

使用jQuery ajax通過使用json或html文件自動刷新/更新表

[英]Autorefreshing/updating table using jQuery ajax by either using json or html files

所以@SOF,

我一直試圖讓我的學校成績,結果,預計成績等網頁都有一個自動更新功能,以便當新數據通過使用jqueryajax以及有一個時,頁面上的數據刷新課程的“單一視圖”。

我的主要問題是我無法獲得任何形式的ajax刷新/加載正常工作,我可以在json或單個html文件中生成我的輸出,為了我的目的,我認為json會更好,但我不確定。

我的網頁左上方有一個導航幫助器,這是一個下拉菜單,通過“搜索”找到的<a id="CLASS1" optionname="CLASS 1"></a>列表填寫。在表格中找到,但是如果需要的話,如果需要,我可以在表格外填充。

理想情況下,我希望能夠修改下拉列表,因此我們在此示例中共有8個選項,包括- Select Class -Class 1Class 2Class 3Class 4Class 5All UpdatingAll Non-Updating

全部更新

  • 此選項將所有類加載到一個html可查看頁面中,並每30秒更新一個類(我說每個類可能會在一小時內更新,其他一些類可能會在不同的時間更新),因此需要進行比較和如果不同然后更新?

所有非更新

  • 此選項將所有類加載到一個html可查看頁面中,但除非用戶單擊其他類(使用下拉列表)然后單擊返回,否則不會更新...

1級,2級,3級......等(單個裝載/單個視圖)

  • 此選項將單個類的數據加載到html可查看頁面中,並且每30秒更新一次該特定類 ,在之前的帖子中,名為Gaby aka G. Petrioli的用戶給出了一個非常接近我需要的示例但是成員永遠不會回到我身邊: http//jsfiddle.net/u7UkS/4/

鏈接到所有數據

HTML - http://pastebin.com/raw.php?i=0PNQGMmn

CSS - http://pastebin.com/raw.php?i=4H5GHv15

JSON - http://pastebin.com/raw.php?i=xk860dBN

單一類頁面 - http://pastebin.com/raw.php?i=HvpaVhG6

JSFiddle - http://jsfiddle.net/kHtuQ | http://jsfiddle.net/kHtuQ/show

某些成員的一些ajax示例的上一篇文章Anchor Cycler / Dropdown定期導入學校班級數據


下面是一個示例,大致顯示每個“類” Note Class = School Class中的內容

Super Slimed Down Table示例:

<table id="gradient-style">
    <tbody>
        <thead>
            <tr>
                <th scope="col"><a id="CLASS1" optionname="CLASS 1"></a>Class</th>
            </tr>
        </thead>
        <tr><td>Class 1</td></tr>
    </tbody>
    <tfoot>
            <tr>
                <th class="alt" colspan="34" scope="col"><a id="KEY"></a><img class="headimager" src="http://placehold.it/250x50"/></th>
            </tr>
            <tr>
                <td colspan="34"><em><b>Data</b> - Test</em></td>
            </tr>
    </tfoot>
</table>

如果有人可以提供幫助,我們將非常感激,如果你能夠發表評論,請這樣做,我可以繼續學習。

謝謝
丹尼斯S.

使用ajax非常簡單,
我建議你使用HTML數據類型,因為你的容器中有一個表,
這里有一個api文檔=> http://api.jquery.com/jQuery.ajax/
這是我為你做的小提琴=> http://jsfiddle.net/sijav/kHtuQ/19/http://fiddle.jshell.net/sijav/kHtuQ/19/show/

我已經將ajax代碼放在一個名為updateClass(url)的函數中,其中url代表要獲取的url,它將使用HTML獲取容器=>

function updateClass(url){
    $.ajax({
        url: url,
        dataType: "HTML",
        error: function(msg){
            alert(msg.statusText);
            return msg;
        },
        success: function(html){
            $("#container").html(html);
        }
    });
}

我添加了一個刷新整個容器類的refreshClass,=>

function refreshClass(){
            updateClass("http://fiddle.jshell.net/sijav/mQB5E/5/show/"); //update the class
}

並將更改選擇器更改為以下代碼=>

var classUpdateI; //stands for our interval updating class
$(".class-selector").on("change",function(){
    if (classUpdateI!=null)clearInterval(classUpdateI); //If the selector changed clear the interval so the container won't be update on it's own
    if(this.value == "")
        return; // if the value is null don't do anything
    else if(this.value == "allclassnup"){
        refreshClass(); //if the value is allclassnup which is stands for All Non-Updating just refresh the whole class 
    }
    else if(this.value == "allclassup"){
        refreshClass(); //if the value is allclassup which is stands for All Updating refresh the whole class and set an interval for thirty second (look for 30*1000)
        classUpdateI = setInterval(refreshClass,30*1000);
    }
    else //else then it's a simple class value, just simply update the current class
        updateClass(this.value);
})

希望能幫助到你 ;)
編輯 :編輯所以它可以獲得大表(不生成它!),所有更新將在30秒的間隔內更新
AnotherEDIT :信不信由你,我已經完成了你的所有問題!
工作時間: http//jsfiddle.net/sijav/kHtuQ/39/http://fiddle.jshell.net/sijav/kHtuQ/39/show/
1這是因為它只用於最后一個html,對於新的我們應該重新制作它! 所以把整個$('tr').click()函數放到另一個函數中,並在必要時調用它。
- 你想讓它完全發揮作用嗎? 它有點復雜但它可以適用於代碼的一些變化! 我要告訴你的是,好的,我們應該將當前類的類選擇器更改為cookie,然后我們可以在刷新或重新加載頁面並放入必要的選定類等時讀取它...
但在這里的代碼設計中,我做了讓它工作,
首先我創建了一個名為FirstTimeInit = true;的全局變量FirstTimeInit = true; 只是為了確定我們是否第一次加載頁面,第二次我把for循環使頁面加載時突出顯示為一個名為selectSelectedClass的函數,為什么? 因為我們需要多次調用它,第三我添加了一些if語句以確定我們是否可以讀取cookie然后更改突出顯示的內容和當前類,這里是代碼:

if(readCookie("CurrentClass")) //if we can read coockie
    $(".class-selector").val(readCookie("CurrentClass")).change(); //change it's value to current cookie and trigger the change function
else{ // else
    selectSelectedClass(); //select those which was highlighted before
    trClick(); //make things clickable
    FirstTimeInit = false; //and turn of the first time init
}

在選擇器值更改上添加創建cookie => createCookie("CurrentClass",$(".class-selector").val(),1);
最后改變了獲得Ajax的成功

        success: function(html){
            $("#container").html(html + '<a id="KEY"></a>'); //the html container changer with adding extra id , I'll explain it later it's for your second question
            if(FirstTimeInit){ //if it is First Time then
                selectSelectedClass(); //highlight which was highlighted after put the correct html
                FirstTimeInit = false; // turn of the first time init
            }
            else //else
                for (var i=0;i<($("table").children().length);i++){
                    if(readCookie(i))
                        eraseCookie(i); //erase every cookie that has been before because the table is now changed and we're going on another table so old cookie won't matter
                }
            trClick(); //make things selectable!
        }

另外,為了使它無bug,我已經將refreshClass改為firstinit,當所選的類是全部或者它是null時,因為那時我們有所有類並且需要那些cookie! 所以這是代碼:

function refreshClass(){
    if(readCookie("CurrentClass")=="allclassnup"||readCookie("CurrentClass")=="allclassup"||readCookie("CurrentClass")==null)
        FirstTimeInit = true;
    updateClass("http://fiddle.jshell.net/sijav/mQB5E/5/show/");
}

2 <a id="TOP"></a>必須在容器之前,在將html放在容器上之后,必須在容器的末尾生成<a id="KEY"></a> 所以$("#container").html(html + '<a id="KEY"></a>');

3 Next和Previous按鈕專為非ajax之前的設計而設計,現在需要一個不同的解決方案! 例如,請參閱這些簡單的代碼

$("#PreviousClass").click(function(){//on prev click
    $(".class-selector").val($(".class-selector option:selected").prev().val()).change() //change the value to the prev on and trigger the change
});

$("#NextClass").click(function () {//on next click
    $(".class-selector").val($(".class-selector option:selected").next().val()).change() //change the value to the prev on and trigger the change
});

4是你有可能你應該更改你的密鑰和下來這些代碼,你很高興=>

currentClass=0;
$("a.TOPJS").click(function () {
    if(currentClass>0){
        currentClass--
        scrollToAnchor('CLASS'+currentClass);
    }
});

$("a.KEYJS").click(function () {
    if($("a[id='CLASS" + currentClass + "']")[0]!=undefined){
        currentClass++
        scrollToAnchor('CLASS'+currentClass);
    }
    else
        scrollToAnchor('CLASSMAX');
});

Godd Luck

另一個請求編輯:(希望這將是最后一個!)
工作小提琴http//jsfiddle.net/sijav/kHtuQ/42/http://fiddle.jshell.net/sijav/kHtuQ/42/show/
好吧,因為你不喜歡更新類刷新到其中的一個我已經刪除了,並且更好我添加了一些代碼在cookie中有類,因為cookie不是樹有某種條件,正在從類選擇器的最后一個字符讀取類,所以請確保在最后一個字符處有類號 - > Class number ***5***將為類選擇器讀取數字5!
編輯 :優化課程下一步和上一頁http://jsfiddle.net/sijav/kHtuQ/46/
編輯 :根據要求的評論,
這就是我想告訴你的,有時在jsfiddle.net上演示,有時它在fiddle.jshell.net上顯示,這些是不同的域,你不能從不同的域獲取HTML。
1)您可能只將函數放入Interval或只是創建另一個函數並按照這樣的方式調用它=>

classUpdateI = setInterval(function(){updateClass(this.value,parseInt(a.charAt(a.length-1),10));},30*1000);

2)失蹤?! 我找不到你的第二個問題了!
3)好吧,... trclick需要改變... to =>

function trClick(tIndex){ //tIndex would be classnumber from now on
    if (tIndex == -1){ //if it is all updating or all non updating
        $("tr").click(function(){ //do the previous do
            $(this).toggleClass('selected').siblings().removeClass('selected');
            if(readCookie($(this).parent().index("tbody"))){
                if(readCookie($(this).parent().index("tbody"))==$(this).index())
                    eraseCookie($(this).parent().index("tbody"));
                else{
                    eraseCookie($(this).parent().index("tbody"));
                    createCookie($(this).parent().index("tbody"),$(this).index(),1);
                }
            }
            else
                createCookie($(this).parent().index("tbody"),$(this).index(),1);
        });
    }
    else{ //else
        $("tr").click(function(){ //on click
            $(this).toggleClass('selected').siblings().removeClass('selected');//do the toggle like before
            if(readCookie(tIndex)){ //if you can read the CLASS cookie, not the current index of table because our table has only one row
                if(readCookie(tIndex)==$(this).index()) //as before if we selecting it again
                    eraseCookie(tIndex); //just erase the cookie
                else{ //else
                    eraseCookie(tIndex); //select the new one
                    createCookie(tIndex,$(this).index(),1);
                }
            }
            else
                createCookie(tIndex,$(this).index(),1); //else if we can't read it, just make it!
        });
    }
}

當我們在Ajax上成功調用它時,我們應該用classNumber => trClick(classNumber);調用它trClick(classNumber);
最后的工作小提琴: http //jsfiddle.net/sijav/kHtuQ/53/http://fiddle.jshell.net/sijav/kHtuQ/53/show/

祝好運

老實說,我發布的代碼很難,主要是因為我不了解JSON示例。 如果您要將平面HTML存儲為JSON值,那么只需將$.ajax HTML轉換為DOM而不是JSON編碼,解析和插入就更有意義了。 話雖這么說, 我將假設JSON 不是一個現實的例子 ,它將采取更多的形式:

{ class_name: "Class 1", description: "Blah Blah Blah" }

考慮到這一假設,這個記錄良好但未經測試的例子應該指向正確的方向。 基本上,我做以下事情:

  • 定義HTML模板
  • 創建一個簡單的模板化函數,將JSON值轉換為HTML模板
  • 使用setInterval調用一個函數來設置一個間隔以輪詢服務器以獲取新數據,該函數使用getJSON我們上次請求的時間戳傳遞給您的JSON生成服務器端腳本

這是我的例子,如果您有任何問題,請告訴我。

<script>
//  I wrapped this in a self-invoking anonymous function to prevent adding new global variables
(function(){
    var SECONDS_TO_POLL = 3
    ,   $parent_node = $('#node-to-append-to')
    ,   last_timestamp = null // this will be a timestamp passed to the server
    ,   template = '<table id="gradient-style"> \
            <tbody> \
                <thead> \
                    <tr>
                        <th scope="col"><a id="{ident}" optionname="{class_name}"></a>Class</th> \
                    </tr> \
                </thead> \
                <tr><td>{class_name}</td></tr> \
            </tbody> \
            <tfoot> \
                <tr> \
                    <th class="alt" colspan="34" scope="col"><a id="KEY"></a><img class="headimager" src="{image}" /></th> \
                </tr> \
                <tr> \
                    <td colspan="34"><em><b>Data</b> - Test</em></td> \
                </tr> \
            </tfoot> \
        </table>';

    /**
    *   simple templating function
    *   @param template String template using bracket vars (e.g. <h1>{message}</h1>)
    *   @param values Object literal (e.g. {message: "Hello"})
    *   @return Rendered HTML template
    */
    var render_template = function(template, values) {
            values = values || {};
            return template.replace(/{([^{}]*)}/g, function(bracketed, clean){
                  var object_value = values[clean];
                  return ['string', 'number'].indexOf((typeof object_value)) > -1 ? object_value : bracketed;
            });
        };

    // this is our polling function, will retrieve the JSON from the server, convert to HTML using template and render to the DOM
    var poller = function(){
        // load the JSON and pass a GET var telling the server what timestamp to query from (e.g. WHERE data.timestamp > last_timestamp)
        $.getJSON('/path/to/json?last_retrieved='+last_timestamp, function(data){
            // render the new data into our HTML template
            var html = render_template(template, data);
            // append the result to the parent DOM node
            $parent_node.append(html);
        })
        // get a current timestamp so that we can limit the server results to those 
        last_timestamp = new Date().getTime();
    }

    // retrieve new results every N seconds
    setInterval(poller, SECONDS_TO_POLL*1000);
})()
</script>

另外,只是為此,如果您只是從服務器返回HTML,您可以(大部分)簡單地用$.get替換$.getJSON ,放棄客戶端的所有模板渲染,只需將響應附加到DOM

(function(){
    var SECONDS_TO_POLL = 3
    ,   $parent_node = $('#node-to-append-to')
    ,   last_timestamp = null // this will be a timestamp passed to the server

    // this is our polling function, will retrieve the HTML from the server and render to the DOM
    var poller = function(){
        // load the HTML pass a GET var telling the server what timestamp to query from (e.g. WHERE data.timestamp > last_timestamp)
        $.get('/path/to/server?last_retrieved='+last_timestamp, function(html){
            // append the result to the parent DOM node
            $parent_node.append(html);
        })
        // get a current timestamp so that we can limit the server results to those 
        last_timestamp = new Date().getTime();
    }

    // retrieve new results every N seconds
    setInterval(poller, SECONDS_TO_POLL*1000);
})()

解決問題的最佳方法是使用綁定庫,例如knockout。 有了它,您可以分離數據和視圖,只需要擔心如何更新數據,視圖就會自動更新。 這就是你目前正在掙扎的東西。

這就是為什么我制作一個小樣本生成一個列表並通過不斷輪詢來更新數據(使用一個總是返回隨機變化的相同數據的虛假服務)。

以下是我使用淘汰賽所做的示例:請查看淘汰賽文檔頁面: http//knockoutjs.com/documentation/introduction.html

HTML:定義包含標題和內容的簡單表

<table style="width: 100%" border="1">
    <thead>
        <tr>
            <td>
                <p><b>Classes</b>   
                </p>
            </td>http://jsfiddle.net/yBat5/#fork
            <td>
                <p><b>Childs</b>
                </p>
            </td>
        </tr>
    </thead>
    <tbody data-bind="foreach: Classes">
        <tr>
            <td>
                <p data-bind=" text: Class"></p>
            </td>
            <td>
                <p data-bind=" text: Child"></p>
            </td>
        </tr>
    </tbody>
</table>

JavaScript的:

$(function () {
   // define a ViewModel for your data
    function ViewModel() {
        this.Classes = ko.observableArray([{
            "Class": "test",
                "Child": "Max"
        }, {
            "Class": "test2",
                "Child": "Walter"
        }]);
    }

    var vm = new ViewModel(),
        dummyData = [];

    // create a lot of dummy data sets
    for (var i = 0; i < 1000; i++) {
        dummyData.push({
            "Class": "test " + i,
                "Child": "Child" + i
        })
    }

    // constantly poll for new data
    // JS fiddle implements a simple echo service, which we can use
    // to simulate data changes we change a rendon number
    function poll() {
        $.ajax({
            "url": "\/echo\/json\/",
                "type": "POST",
                "data": {
                "json": JSON.stringify(dummyData),
                    "deley": 3
            },
                "success": function (data) {
                vm.Classes(data);

                // poll again (3 seconds so we see how fast the update is)
                setTimeout(poll, 300);

                    // change a random entry to see that data changes
                var randomnumber=Math.floor(Math.random()*1000);
                    dummyData[randomnumber].Child = "Child"  +randomnumber +" changed"
            }
        });
    }

    poll();

    // apply it to the page, knocout now does the binding for you
    ko.applyBindings(vm);
});

小提琴: http//jsfiddle.net/yBat5/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM