2016-07-26 51 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'對象 –