【问题标题】:jQuery Ajax each function check return ID is the same as the previous onejQuery Ajax每个函数检查返回ID是否与上一个相同
【发布时间】:2020-05-25 10:37:16
【问题描述】:

我正在使用 AJAX 从删除服务器中获取数据,然后我使用 each 循环。

现在我想做的是如果返回值数据和之前的一样我做点什么 我有 10 个 val.userId == 1 ,我只想做一次而不是 10 次。

在实际情况下,我不知道我想让它动态化的用户 ID 怎么样 狐狸示例用户 12123 有 10 次,用户 1239823 有 1000 次

例如这里 https://jsonplaceholder.typicode.com/posts

$(document).ready(function(){
        getData();
      });


function getData(){
    $.ajax({
          type: "GET",
          url: "https://jsonplaceholder.typicode.com/posts",
          dataType: 'json',
          success: function(response){

              $.each(response, function(index, val) {
                console.log(val); // get all return data
                // as we can see userId == 1 have 10 posts , I just want to console.log only once if usdId == 1
                if(val.userId == 1){
                  console.log(val.userId);  // this one consoloe .log 10 times since we have 10 userId 
                }
                // how about in the real case I do not know the user ID i wanna make it dynamic
                // fox example user 12123  has 10 times ,  user 1239823 has 1000 times 

              });


          },
          error: function(xhr, textStatus, error){console.log(xhr.statusText);console.log(textStatus);console.log(error);

          }
    });
  }

感谢阅读

【问题讨论】:

    标签: javascript jquery json loops each


    【解决方案1】:

    如果要删除基于userId 的重复项,可以使用响应进行循环并过滤它们。

    $(document).ready(function(){
        getData();
    });
    
    
    function getData(){
        $.ajax({
              type: "GET",
              url: "https://jsonplaceholder.typicode.com/posts",
              dataType: 'json',
              success: function(response){
                  var arr = [];
                  
                  response.forEach(function (item) {
                    var result = arr.find(x => x.userId === item.userId);
                    if (!result) {
                      arr.push(item);
                    }
                  });
                  
                  console.log(arr);
              },
              error: function(xhr, textStatus, error){            
                  console.log(xhr.statusText);
                  console.log(textStatus);
                  console.log(error);
              }
        });
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2015-12-24
      • 2020-07-27
      • 2015-12-12
      • 2020-01-05
      • 2021-10-01
      • 1970-01-01
      • 2020-10-07
      • 2022-12-03
      • 1970-01-01
      相关资源
      最近更新 更多