我正在使用 AJAX 从删除服务器获取数据,然后使用 every 进行循环。
现在我想做的是如果返回值数据与之前的相同我就做一些事情 我有 10 val.userId == 1 ,我只想做一次而不是 10 次。
在实际情况下我不知道用户ID我想让它动态怎么样 Fox示例用户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);
}
});
}
感谢您的阅读
最佳答案
如果您想根据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>
关于javascript - jQuery Ajax每个函数检查返回ID是否与前一个相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60144829/