首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要xml数据来保持每2秒发送一次,直到收到响应

需要xml数据来保持每2秒发送一次,直到收到响应
EN

Stack Overflow用户
提问于 2013-08-09 02:55:27
回答 2查看 80关注 0票数 0

这是一个非常小的原型/实验应用程序。设备经常进入休眠状态以节省电池寿命,用户将访问本地网页并按下按钮来更改设备的某些内容,这将使用下面的javascript代码向设备发送POST。

由于当用户按下按钮时设备可能处于休眠状态,因此它将错过POST。我知道这是不好的做法,但我基本上需要网页保持发布(甚至不知道我是否使用了正确的术语)或发送数据,直到它收到响应。我尝试了一次while循环,但它只发送了一次,可能我把它放错了地方。

代码语言:javascript
运行
复制
function execPOST(url, postData, callback) {
    var postRequest = newAjaxRequest();
    postRequest.onreadystatechange = function() {
        if (postRequest.readyState == 4) {
            if (postRequest.error) {
                callback(1, "Request had an error.");
                alert('postRequest Error');
            } else {
                var status;
                try {
                    status = postRequest.status;
                } catch (err) {
                    callback(1, "Failed to get HTTP status from server.");
                    return;
                }
                if (status == 200 || status == 0) {
                    callback(0, postRequest.responseText);
                } else {
                    callback(1, "POST: Unexpected HTTP Status: "
                            + postRequest.status);
                    alert('POST: Unexpected HTTP Status: '
                        + postRequest.status);
                }
            }
        }
    }
    if (postRequest.overrideMimeType){
        postRequest.overrideMimeType("text/xml");
    }
    postRequest.open("POST", url, false);
 //I tried adding this while loop hoping it would keep sending but it only sent once
    while (postRequest.readystate != 4)
    {
        setTimeout('',2000);
        postRequest.send(postData);
    }
    return postRequest;
}
EN

回答 2

Stack Overflow用户

发布于 2013-08-09 03:03:10

我建议使用socket.io在循环中"ping“设备,直到它唤醒,然后发送POST请求。

票数 1
EN

Stack Overflow用户

发布于 2013-08-09 03:15:12

你有没有考虑过使用jquery?

代码语言:javascript
运行
复制
function ping () {
    $.ajax (
          <url>
        , {
              error:    function ( jqXHR, textStatus, errorThrown ) {
                        }
            , timeout:  5000    // in ms
            , type:     'POST'
          }
    }).done(function ( data, textStatus, jqxhr ) {
        // whatever
    }).fail(function ( jqxhr, textStatus, data ) {
        // note that the order of arguments is different from that of the success handler ('done') !
        if (textStatus === 'timeout') {
            ping();
        }
        else {
            // ... more error handling
        }
    });

有关更多信息,请访问consult the docs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18133892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档