获取ajax请求的最佳方式是什么。
每次调用javascript函数时,我都会变得越来越快 我不知道为什么。这是代码:
$(function(){
getSuggestions();
});
function getSuggestions(){
var url = $("#baseUrl").val() + '/placement/suggestions/x-fetch-suggestions';
var data ={}
var result = myAjaxJson(data,url); //gets json object via ajax
/* gets object 'sug' and put into #suggestions-list*/
$('#suggestions-list').html(result.sug);
var a = setInterval("getSuggestions()",5000);
}
答案 0 :(得分:3)
你那里有一个递归的双环。
试试这个:
$(function(){
var a = setInterval("getSuggestions()",5000);
});
function getSuggestions(){
var url = $("#baseUrl").val() + '/placement/suggestions/x-fetch-suggestions';
var data ={}
var result = myAjaxJson(data,url); //gets json object via ajax
/* gets object 'sug' and put into #suggestions-list*/
$('#suggestions-list').html(result.sug);
}
答案 1 :(得分:2)
每次调用getSuggestions时都会启动新的setInterval。把它放在外面:
$(function(){
var a = setInterval("getSuggestions()",5000);
});
保证
$(function(){
getSuggestions();
});
从getSuggestions方法中删除setInterval代码。
答案 2 :(得分:0)
不要使用setInterval,请使用setTimeout。无论先前的Ajax请求是否完成,setInterval每5秒调用一次该函数。 setTimeout将在上一个Ajax请求之后等待5秒,以启动下一个。:
$(function(){
getSuggestions();
});
function getSuggestions(){
var url = $("#baseUrl").val() + '/placement/suggestions/x-fetch-suggestions';
var data ={}
var result = myAjaxJson(data,url); //gets json object via ajax
/* gets object 'sug' and put into #suggestions-list*/
$('#suggestions-list').html(result.sug);
var a = setTimeout("getSuggestions()",5000);
}
答案 3 :(得分:0)
var counter = 0;
var timer = null;
function loader(){
if (timer) {
clearTimeout(timer);
timer = null;
return;
}
timer = window.setInterval(function(){
$("#paragraph").load("file.php");
}, 10);
}
window.onload = function() {
loader();
};