[英]getJSON done callback
我有每5秒调用一次的函数bellow以从服务器获取数据,这是flask / python。 我的问题是,当成功检索数据时,如何使getjson调用具有回调功能。
我知道有.done .fail等等,但我想知道是否可以保留此结构并仅添加以下内容,但我不了解这种特殊情况的语法,希望这不会造成混淆,谢谢阅读,这是代码。
// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
// request timesince table entries from server for user...
$.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // do something with the response data
timesince_dataBuffer = data;
});
return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);
你可以做这样的事情。 不用处理getData
的数据或使用回调,而要利用$.getJSON
返回的承诺 。 有一个单独的函数,该函数由超时调用,该超时调用数据, then
处理。 它巧妙地将您的代码分离为更易于管理的功能。
var getDataFromServerInterval = 5000;
function getData() {
return $.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}
}
function wrangleData() {
getData().then(function (data) {
console.log(data);
});
}
setInterval(wrangleData, getDataFromServerInterval);
我找到了一个部分解决方案,我意识到我可以在函数的末尾添加一个回调来处理接收到的数据,这在不同的getjson调用结构中等效于.done,我不确定该函数是否在接收数据之前或之后调用。
// global timesince buffer, holds
var timesince_dataBuffer;
// get data from the server every getDataFromServerInterval milliseconds
var getDataFromServerInterval = 5000;
function getData(){
// request timesince table entries from server for user
$.getJSON($SCRIPT_ROOT + '/_database', {
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // do something with the response data
timesince_dataBuffer = data;
updateEntryStruct(); // the hope is to call this when data is received
});
return false; // prevent get
}
// get data from the server every getDataFromServerInterval milliseconds
setInterval(getData, getDataFromServerInterval);
这是我想出的解决方案。
var timesince_dataBuffer;
function getData(){
// gets user's entries from sql table
$.getJSON($SCRIPT_ROOT + '/_database', { // $SCRIPT_ROOT, root to the application
action: "getUserTable_timesince",
username: $('input[name="username"]').val()
}, function(data) { // if a response is sent, this function is called
timesince_dataBuffer = data;
updateEntryStruct(); // recreate the structure of each content, buttons etc
});
return false;
}
我得到数据,将其放在全局变量中,调用另一个函数,该函数接收该数据并为接收到的每个对象重新创建一个结构,这样,我就不会重新创建静态的结构部分,最重要的是按钮。
每1秒调用另一个功能,该功能会更新动态部件。 自(事件名称)以来经过的(格式化时间)
无论如何,这实际上是我在CS50中完成的最后一个项目,我首先通过表单提交与服务器进行通信,每次用户按下按钮时刷新页面,然后通过ajax完成,但是我每2次向服务器发送一次请求秒,并具有无响应的按钮,因为我会在一段时间间隔内自行重新创建按钮。 现在,页面让您感到响应迅速且高效,这已经是一个很棒的学习体验。
如果有人想签出代码,一切都在这里。 https://github.com/silvermirai/cs50-final-project
我想到的基本上是一堆随机功能。 到目前为止,可以在这里找到该应用程序。 http://ide502-silvermirai.cs50.io:8080/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.