在javascript中搜索ajax请求元素的索引

Search the index of an ajax request element in javascript

本文关键字:元素 索引 请求 ajax javascript 搜索      更新时间:2023-09-26

我有一个ajax响应,其中包含从sql查询中提取的数据。它有这样的结构:

Response
   id:"id"
   titulo:"title"
   url:"url"

我试图做的是在ajax响应中找到给定唯一id所在的位置。

$.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,知道数字应该在第一个位置。

编辑:我需要这个位置,以便通过增加"index"开始在数组中移动response[index].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);
    }
});