我有一个javascript函数,它每隔一定时间生成一次JSON数据,然后将它放到云服务器上。现在我不想实时发布,而是想将这些数据记录在一个缓冲区中,并说在n个数据日志后我将PUT转为云。例如,我想在10秒内记录50个数据点,然后使用时间戳我将PUT发送到服务器
现在JSON数据通过var fromDatan
传递。 JSON数据格式是
{"value":"-2.1282838391939194"}
现在代码是:
var acc;
var watchID = null;
function startWatch() {
//set frequency of accelerometer update.1000 = 1 second
var options = { frequency: 1000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
//DISPLAY ACCELERATION DATA
function onSuccess(acceleration) {
acc = acceleration;
var element = document.getElementById("accelerometer");
element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
datalock();
}
function postdata () {
var accx = acc.x;
alert(accx);
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
//POST JSON SENSOR DATA
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
//var fromData = {};
}
var fromData;
var jsonCounter = 0;
function datalock(){
alert("Entering");
fromData.push({
value: accx.toString(),
});
jsonCounter++;
// post only after 10 entries
if (jsonCounter >= 10) {
postdata ();
jsonCounter = 0; // reset
};
//var fromData; // make it global as it is used in other function.
}
但是代码现在还没有用。请告诉我问题所在。虽然所有其他事情都是正确的,推动我无法正确实施。有人可以帮帮我吗?它正在点击“输入警报。就是这样。不会发挥作用postdata()