Send xmlHttpRequest every 10 second in JavaScript
I run a JavaScript function that send a xmlHttpRequest
to an .ashx
(let's name it send_req()
that run on page load for first time). For onreadystatechange
, I have a function that receive XML data and show it on the page (let's name this one getanswer()
).
I want to automatically update XML data on the page every 20 seconds. For that, I use setTimeout(send_req(),20000)
in the end of writexml()
, but it doesn't update data on the page. I add an alert()
at the ****
line in the code. It shows on the page every one second!
And my code works fine if I use it without setTimeout
.
Here is my code
var Population = "";
var Available_money = "";
var resource_timer;
var httpReq_resource;
function send_req() {
if (windo开发者_开发百科w.ActiveXObject) {
httpReq_resource = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
httpReq_resource = new XMLHttpRequest();
}
var sendStr = "user_id=1";
if (httpReq_resource)
{
httpReq_resource.onreadystatechange = getanswer;
httpReq_resource.open("POST", "Answer_Resource_change.ashx");
httpReq_resource.send(sendStr);
}
}
function getanswer() {
var results = httpReq_resource.responseXML;
if (httpReq_resource.readyState == 4) {
if (httpReq_resource.status == 200) {
try {
var value;
var values = results.getElementsByTagName("values");
for (var i = 0; i < values.length; i++) {
value = values[i];
Population = value.getElementsByTagName("Population")[0].firstChild.nodeValue;
Available_money = value.getElementsByTagName("Available_money")[0].firstChild.nodeValue;
... and some more like two line up
}
make_changes();
**********************************
resource_timer = setTimeout(send_req(), 20000);
}
catch (e) {
}
}
}
}
function make_changes() {
$("li span#l1").text(Available_money + '/' + Population);
...and some more like up line
}
This:
resource_timer = setTimeout(send_req(), 20000);
Should be:
resource_timer = setTimeout(send_req, 20000);
The first executes the result of send_req()
after 20 seconds, the second executes send_req
itself.
精彩评论