我正在生成动态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>");
}
}
});
}
});
答案 0 :(得分:3)
首先,将现有代码(循环和ajax调用)包含在函数中。然后,您可以使用 recursion 创建 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调用的本质。它将阻止您的脚本,直到请求完成。
干杯!
答案 1 :(得分:0)
设置一个十秒的计时器并调用Ajax方法,我认为这将解决您的问题