jquery: load values from external html and populat

2019-07-23 09:19发布

问题:

I'm using this code now, works great except that it makes three requests to the webserver:

var refreshspeed=1000

        function moreSnow() {
    $("#uptimedynamic").load("index.html #uptimedynamic");
    $("#cpuloaddynamic").load("index.html #cpuloaddynamic");
    $("#meminfodynamic").load("index.html #meminfodynamic");
    setTimeout("moreSnow()", refreshspeed);
    }

Can someone tell me how to make it do the same thing, but with only one read of index.html? It needs to stay in the same repeating loop setup :)

回答1:

This should do it

/* cache selectors in main page to avoid searching for them every second*/
var $upTime=$("#uptimedynamic"),  $cpuload = $("#cpuloaddynamic"), $meminfo=$("#meminfodynamic")


function moreSnow() {
    $.get("index.html", function(data){
        /* create a jQuery object from the retrieved page html that can then be traversed*/
        var $data=$(data);

        $upTime.html( $data.find('#uptimedynamic').html() );
        $cpuload.html( $data.find("#cpuloaddynamic").html() );
        $meminfo.html( $data.find("#meminfodynamic").html() );

    });
}

By retrieving only the contents of each element you alsoo avoid dupicating ID's in page and potential style issues