我有一个 ajax 响应,其中包含从 sql 查询中提取的数据。它有这样的结构:
Response
id:"id"
titulo:"title"
url:"url"
我想做的是找到给定唯一 ID 在 ajax 响应中的位置。
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
console.log(response);
console.log(response.indexOf(27188964));
}
});
第二个日志打印-1
,知道数字应该在第一个位置。
编辑:
我需要这个位置才能通过增加“索引”开始在数组中移动
响应[索引].url
最佳答案
如果您的响应是一个对象数组,您可以使用 Array.prototype.filter() :
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
var resultIndex;
var result = response.filter(function(obj, index) {
if (obj.id === '27188964') {
resultIndex = index;
return true;
}
return false;
});
console.log('resultIndex:', resultIndex);
console.log('result:', result);
}
});
关于javascript - 在javascript中搜索ajax请求元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585986/