我有以下json数据,它位于网址http://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
的值id
等于1
,并使用jquery将它们存储为变量。
我知道有一种方法,
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
console.log(data);
});
但我不知道如何实现它。任何人都可以帮我找到解决方案吗?
答案 0 :(得分: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 。
答案 1 :(得分: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)
}
});
答案 2 :(得分: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
});
答案 3 :(得分:0)
请阅读此链接上提供的文件