在JavaScript中每10秒发送一次xmlHttpRequest

ham*_*mze 1 javascript xmlhttprequest

我运行发送一个JavaScript函数xmlHttpRequest.ashx(让我们命名它send_req()是对第一次页面加载运行).因为onreadystatechange,我有一个接收XML数据并在页面上显示它的函数(让我们将其命名为getanswer()).

我想每20秒自动更新页面上的XML数据.为此,我setTimeout(send_req(),20000)在最后使用writexml(),但它不更新页面上的数据.我添加alert()****代码行.它每隔一秒显示在页面上!

如果我没有使用它,我的代码工作正常setTimeout.

这是我的代码

var Population = "";
var Available_money = "";
var resource_timer;
var httpReq_resource;

function send_req() {
    if (window.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
}
Run Code Online (Sandbox Code Playgroud)

Fél*_*lli 6

这个:

resource_timer = setTimeout(send_req(), 20000);
Run Code Online (Sandbox Code Playgroud)

应该:

resource_timer = setTimeout(send_req, 20000);
Run Code Online (Sandbox Code Playgroud)

第一执行结果send_req()20秒后,第二执行send_req本身.