【问题标题】:AJAX - Make API call based on intervalAJAX - 根据间隔进行 API 调用
【发布时间】:2020-06-09 20:18:19
【问题描述】:

我有 2 个 AJAX 函数指向不同的 Node.js 路由。第二个 AJAX 调用在按钮单击时触发。 要求 - 第二个 AJAX 函数需要从后端 Node 应用程序接收实时数据,并使用新数据每隔 5 secs 重新加载页面。

index.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() 或完全不同的方法?

【问题讨论】:

    标签: javascript jquery node.js ajax


    【解决方案1】:

    像这样。我不建议在 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>

    【讨论】:

    • 好吧,代码对我来说工作正常,除了我的success 中的函数很少,它在每个 API 调用上将数据附加到HTML table,我不希望这种情况发生。有没有办法防止这种情况发生,即每次在 5 秒后进行 API 调用时,它都不应该将新数据附加到表中。休息看起来不错。
    • 另外我不完全理解 ECMA 脚本,我想坚持 Vanilla JS 的传统语法。
    • 我在success中很少有函数可以根据从后端获取的数据生成图表。其中之一是处理我不想在每个 setInterval() 上更改的 HTML 表格数据。休息应该反映新数据,而不是 HTML 表格附加功能。希望这能给我的期望带来一点透明度。
    猜你喜欢
    • 2017-11-12
    • 2017-11-26
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多