在http请求中发送持续时间的数据

时间:2011-12-09 04:37:49

标签: http time request duration

嗨,这是我使用http请求将数据发送到服务器的js代码。代码工作正常,我可以获取数据但我希望一旦我调用此函数自动发送数据每10分钟。任何人都可以帮助我。提前谢谢

xmlHttp=new XMLHttpRequest();
var url="http://localhost";
xmlHttp.open("POST",url,true);
var params = "lorem=ipsum&name=binny";
function timerMethod() 
{
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.send(params);
}

1 个答案:

答案 0 :(得分:0)

从问题中确切地说出你想要的东西有点困难,但是你在找这样的东西吗?

// Declare variables
var timedUpdate, getRequestParams, url, updateTimeout;

// Define timedUpdate function
timedUpdate = function () {

    // Declare variables
    var xmlHttp, params;

    // Create a new AJAX object
    xmlHttp = new XMLHttpRequest();

    // Define a call back function
    xmlHttp.onreadystatechange = function () {

        if (xmlHttp.readyState < 4) {
            return; // Only do something if the request if complete
        }

        if (xmlHttp.responseCode != 200) {
            // Handle HTTP errors here
            // e.g.
            alert('Something went wrong with the AJAX request (HTTP '+xmlHttp.responseCode+')');
        }

        // Do your thing with the returned data

        // Set the function to run again after updateTimeout seconds
        setTimeout(timedUpdate, updateTimeout * 1000);
    };

    // Get the request parameters
    params = getRequestParams();

    // Send the request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.send(params);

};

// Define getRequestParams function
getRequestParams = function () {
    // This function returns a parameter string to be used in the request
    // I am guessing you need to generate a new one every 10 minutes
    return "lorem=ipsum&name=binny";
};

// Define the URL to be used in the requests
url = "http://localhost/";

// Define how often the function is repeated, in seconds
updateTimeout = 600; // 10 minutes

// Make the first call to the function
timedUpdate();