[英]Get data from Json using jquery
I have the following json data, which is located in the url http://localhost/stock/index.php/masterfiles/itemgriddata
我有以下json数据,这些数据位于url
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"}]
I want to get the value of name
and code
where id
equal to 1
, and store them as variables using jquery . 我想获取
id
等于1
的name
和code
的值,并使用jquery将它们存储为变量。
I know there is a method like, 我知道有一种方法,
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
console.log(data);
});
but I don't know how to implement it. 但我不知道如何实现。 Can any one help me find the solution?
谁能帮我找到解决方案?
$.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;
}
})
});
But if you want to store all result in array then: 但是,如果要将所有结果存储在数组中,则:
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;
);
})
});
You can iterate over the array and check for the object which has id "1" as 您可以遍历数组并检查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)
}
});
You can try something like: 您可以尝试如下操作:
$.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
});
please read documents available on this link 请阅读此链接上可用的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.