使用ajax json基于`id`获取数据的值

时间:2017-02-22 05:39:58

标签: javascript jquery json ajax

我有json格式的数据,我试图用ajax成功地向她展示。但是如何使用ajax在json中找到一个id?以及脚本我是否正确?例如,我想找到id 2

我的json

{ "device": [
    {
        "id": 1,
        "name": "Android"
    },
    {
        "id": 2,
        "name": "Apel"
    },
    {
        "id": 3,
        "name": "Windows"
    }
] }

我的ajax

$(document).ready(function() {
    var id_pm = 2 ;
    var dataString = "id="+id_pm;   
    $.ajax({
        type: "GET",
        url: "data.json",
        data: dataString,
        cache: false,
        timeout: 3000,
        error: function(){
            alert('Error');
        },              
        success: function(result){
            var result=$.parseJSON(result);
            $.each(result, function(i, element){        
                var id=element.id;
                var name=element.name;  
            }); 
        }
    });
}); 

2 个答案:

答案 0 :(得分:1)

我的ID是唯一的。如果您的JSON不包含顺序ID,则您必须按顺序扫描所有对象:

//put this inside your success callback.
var mysearchId = 2;
//res is now array of all your devices.
var res = (JSON.parse(result)).device;
for(var i = 0;i < res.length;i ++) {
    if(res[i].id == mysearchId) {
      console.log(res[i]);
      return;
    }
}
console.log('not found!');

这在O(N)时间内找到所需的项目。

如果你的id是顺序的,你可以在O(1)时间内找到一个特定的元素。为此,必须对devices数组进行排序。 例如,如果您要查找ID为10的元素,则可以res[(10-1)]; //==>res[9];访问该元素,前提是第一个项目的id = 1。

答案 1 :(得分:0)

您可以使用过滤功能根据ID

过滤数据
var data = {
            "device": [
         {
             "id": 1,
             "name": "Android"
         },
         {
             "id": 2,
             "name": "Apel"
         },
         {
             "id": 3,
             "name": "Windows"
         }
            ]
        };

        var res = data.device.filter(function (obj) {
            return obj.id == 2;
        });

 if(res.length){
  console.log(res[0].id);
  console.log(res[0].name);
}