簡體   English   中英

如何使用ajax刷新動態生成的div?

[英]how to refresh dynamically generated divs using ajax?

我正在生成動態div,需要每10秒刷新一次。 之前我使用元刷新,但不喜歡頁面閃爍。 我試圖插入ajax代碼,但失敗了。

下面是我沒有ajax的代碼,請告訴我如何以及在何處插入ajax刷新代碼。

$(document).ready(function (){
    var n = 9;
    for(var i=0; i<n; i++){
        var div = document.createElement('div');
        div.className = "d5";
        div.id=i+1;
        // alert(div.id);
        document.getElementById('container').appendChild(div);
        $.ajax({ 
            async    : false,                                      
            url      : 'myapi.php',    //the script to call to get data          
            data     : "",             //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
            dataType : 'json',         //data format      
            success  : function(data){ //on recieve of reply
                var Name       = data[2];
                var subdomain  = data[15];
                var uniqueid   = data[1];
                var shop_photo = data[3];
                var offer      = data[19]; //get id
                //var vname    = data[1];  //get name
                //$('#'+div.id).html("<a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a>"); 
                //$('#'+div.id).html("<img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a><br>Special Offer<br><p>"+offer+"</p>");
                if(offer == ""){
                    $('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a></div></div>");
                }else{
                    $('#'+div.id).html("<div class='div1'><img class='shopperspic' src='b2b/shop_image/"+uniqueid+"/"+shop_photo+"' alt='' /></div><div class='div2'><a href='http://www."+subdomain+".shoppinonline.com'>"+Name+"</a></div><div class='div3'>Special Offer<br class='br_special'>"+offer+"</div></div>");
                }
            } 
        });
    }
});

首先,將您現有的代碼(循環和ajax調用)封裝在一個函數中。 然后,您可以使用遞歸創建setTimeOut循環,並每10秒調用一次函數。

$(document).ready(function(){

  timeout();
  function timeout() {
     setTimeout(function () {
        //Call the function that makes the ajax request
        //This code will re-execute after every 10 seconds
         timeout();
     }, 10000);
} 
});

另外,執行async: false ,實際上是在濫用ajax調用的本質。 它將阻止您的腳本,直到完成請求為止。

干杯!

設置一個十秒計時器並在其中調用Ajax方法,我認為這將解決您的問題

暫無
暫無

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

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