我有一个Ajax函数(ajaxRequest),我想在一段特定时间(比如5秒)后自动运行,没有任何用户提示或警告。我怎样才能做到这一点? (我查看了以下链接,但没有找到解决方案)
jQuery: How to make an AJAX request and continue without waiting for request to complete?
How do I run ajax request in background continuously?
How to run ajax call in background after some particulate time?
How to run execute page in background using ajax?
//My Code
//ajaxRequest Script..
<script type="text/javascript">
function ajaxRequest(map){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'json_data.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
setMarkers(map,myArr);
}
};
xmlhttp.send(null);
}
</script>
<script>
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var lat=51.508742;
var lng=-0.140850;
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas,mapOptions);
ajaxRequest(map); //Called ajaxRequest
}
</script>
答案 0 :(得分:2)
mymap()
后,运行5sec
中的ajax请求触发器。
如果您需要在页面加载时运行ajax,请执行以下操作:
<script>
setTimeout(function() {ajaxRequest(map);},5000);
</script>
直接放在script
<script type="text/javascript">
function ajaxRequest(map){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'json_data.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
setMarkers(map,myArr);
}
};
xmlhttp.send(null);
}
</script>
<script>
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var lat=51.508742;
var lng=-0.140850;
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas,mapOptions);
setTimeout(function() {ajaxRequest(map);},5000); //Called ajaxRequest
}
</script>
答案 1 :(得分:2)
如果您想在每5秒后执行一次ajax调用,请尝试以下操作:
setInterval (function() {
ajaxRequest(map);
}, 5000);
答案 2 :(得分:2)
如果您希望在使用setTimeout()后执行代码,如果您希望每x秒执行一次代码,则可以使用setInterval()。
setTimeout(function() {
//The code you want to execute after 5 seconds
}, 5000);
//OR
setInterval(function() {
//The code you want to execute every 5 seconds
}, 5000);
答案 3 :(得分:2)
您好这是自动发送ajax请求的解决方案
只要把你的功能放在这个。
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var lat=51.508742;
var lng=-0.140850;
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas,mapOptions);
setInterval(function()
{
ajaxRequest(map);
}, 5000);
}
答案 4 :(得分:1)
使用setTimeout(fn, time)在指定时间(ms)后调用该函数一次,或使用setIntreval(fn, time)在指定时间内重复调用该函数
答案 5 :(得分:1)
试试这个......
setTimeout(function() {
//post your ajax code here
}, 1000);
有关详情,请点击http://www.w3schools.com/jsref/met_win_setinterval.asp