jquery: load values from external html and populate many local <div> fields, with one read of the html

牧云@^-^@ 提交于 2019-12-24 16:53:23

问题


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



来源:https://stackoverflow.com/questions/14028480/jquery-load-values-from-external-html-and-populate-many-local-div-fields-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!