2016-07-26 18 views
1

我对从sql查询中提取的数据有一个ajax响应。它有这样的结构:在javascript中搜索ajax请求元素的索引

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

编辑: 我需要为了通过增加“索引” response[index].url

+0

什么它是否意味着响应指数? – Ray

+0

你能否贴上回应? – brk

+0

indexOf通常在搜索词没有结果时返回-1。 –

回答

4

如果你的反应是对象的数组,你可以使用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); 
    } 
}); 
+1

这是一个很好的答案,但并不完整,我仍然需要响应数组中的位置。 – cargide

+0

@cargide你能回复吗? –

+0

@cargide更新了答案正确GET'resultIndex'和'result'对象 –