0

我有以下 json 数据,位于 urlhttp://localhost/stock/index.php/masterfiles/itemgriddata

[{"name":"asdasd","code":"123","id":"1","unit":"Nos","purprice":"25000"},{"name":"Item2","code":"1235","id":"2","unit":"Nos","purprice":"0"}]

我想获取 的值name和等于的值code,并使用 jquery 将它们存储为变量。id1

我知道有一种方法,例如,

$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
  console.log(data);
});

但我不知道如何实现它。任何人都可以帮我找到解决方案吗?

4

3 回答 3

3
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
  $.each(data, function(index, val) {
      if( val.id == '1'){
        var name = val.name,
            code = val.code,
            unit = val.unit,
            purprice = val.purprice,
            id = val.id;
      }
  })
});

但是,如果您想将所有结果存储在数组中,那么:

var dataarr = [];
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
  $.each(data, function(index, val) {
      if( val.id == '1'){
        dataarr.push(
            val.name,
            val.code,
            val.unit,
            val.purprice,
            val.id;
       );
  })
});

有关更多详细信息,请参阅doco

于 2012-08-14T07:45:01.817 回答
1

您可以遍历数组并检查 id 为“1”的对象

arr = [{"name":"asdasd","code":"123","id":"1","unit":"Nos","purprice":"25000"},{"name":"Item2","code":"1235","id":"2","unit":"Nos","purprice":"0"}]

$.each(arr, function(i,ele){
 if (ele.id =="1"){
  alert(ele.name)
  alert(ele.code)
 }
});
于 2012-08-14T07:51:18.297 回答
1

您可以尝试以下方法:

$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
  var results = [];

  $.each(data, function(key, val) {
    if (val.id === "1") {
        results.push(val.name);
        results.push(val.code);
    }
  });
  // Then you can do whatever you want to do with results
});
于 2012-08-14T07:52:41.383 回答