[英]Observable.interval AJAX Call - How to Make Call Before Interval
[英]AJAX - Make API call based on interval
我有 2 个 AJAX 函数指向不同Node.js
路由。 第二个 AJAX 调用在按钮单击时触发。 要求 - 第二个 AJAX function 需要从后端节点应用程序接收实时数据,并每5 secs
使用新数据重新加载页面。
索引.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
// Some function
}
});
$("#myButton").click(function(){
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
success: function (res) {
//This part needs to be excuted/make API call at each interval
//It gets the updated data from backed and reloads every 5 secs
//Below is the logic where I am appending to HTML table
//I don't want this part to be appended with new data wrt setTimeout()
$.each(res.result1, function(key, value) {
console.log("Index",key);
console.log("Item",value);
tableData='<tr><td><a onclick="demoDiv()">'+value+'</a></td><td>'+res.result2[key]+'</td></tr>';
$('#table1').append(tableData);
});
//No changes need for rest of the code
},
beforeSend: function() {
//ABC
},
complete: function() {
//ABC
},
});
});
});
</script>
我该如何使用setInterval()
、 setTimeout()
或完全不同的方法?
像这样。 我不建议在 ajax 上使用 setInterval
const route2 = function() { // or () => {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
success: function(res) {
let tableData = [];
$.each(res.result1, function(key, value) {
tableData.push('<tr><td><a onclick="demoDiv()">' + value + '</a></td><td>' + res.result2[key] + '</td></tr>');
});
$('#restab').html(tableData.join("")); // use .html() to not append
// here you have the rest of the function
},
beforeSend: function() {
//ABC
},
complete: function() {
setTimeout(route2, 5000)
}
});
};
$(function() {
route2();
})
循环示例
const res = { result1: ['127.0.0.1:27018', '127.0.0.1:27019', '127.0.0.1:27020'], result2: ['PRIMARY', 'SECONDARY', 'SECONDARY'] } let tableData = [] $.each(res.result1, function(key, value) { tableData.push('<tr><td><a onclick="demoDiv()">' + value + '</a></td><td>' + res.result2[key] + '</td></tr>'); }); $('#restab').html(tableData.join(""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/> <table class="table" id="table1"> <thead> <tr> <th>Hostname</th> <th>Status</th> </tr> </thead> <tbody id="restab"> </tbody> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.