这是一个非常小的原型/实验应用程序。设备经常进入休眠状态以节省电池寿命,用户将访问本地网页并按下按钮来更改设备的某些内容,这将使用下面的javascript代码向设备发送POST。
由于当用户按下按钮时设备可能处于休眠状态,因此它将错过POST。我知道这是不好的做法,但我基本上需要网页保持发布(甚至不知道我是否使用了正确的术语)或发送数据,直到它收到响应。我尝试了一次while循环,但它只发送了一次,可能我把它放错了地方。
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;
}发布于 2013-08-09 03:03:10
我建议使用socket.io在循环中"ping“设备,直到它唤醒,然后发送POST请求。
发布于 2013-08-09 03:15:12
你有没有考虑过使用jquery?
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。
https://stackoverflow.com/questions/18133892
复制相似问题