这是从Web服务URL获取的JSON响应。 JSON:
{
"data":[
{
"outputQty":"2",
"orderSummaries":[],
"categoryName":"test",
"itemId":1,
"recipes":[],
"name":"Laddu"
},
{
"outputQty":"2",
"orderSummaries":[],
"categoryName":"Badam Pista Mundiri",
"itemId":2,
"recipes":[],
"name":"Barpi"
}
]
}
我试图在html页面中获取JSON值。所以我尝试了如下所示:
$.ajax({
type: "GET",
url: "http://tomcatworkbench.com/Catering2/secured/getAllItems",
dataType: "json",
success: function(response) {
$.each(response, function(idx, obj) {
console.log(obj);
});
}
});
或
$.getJSON("http://tomcatworkbench.com/Catering2/secured/getAllItems", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
两种方式只返回对象我无法获取字符串值。请任何人帮我解决这个问题。谢谢。
答案 0 :(得分:2)
你必须得到rob/chong
对象。
data.data
$.getJSON("http://tomcatworkbench.com/Catering2/secured/getAllItems", function(data){
$.each(data.data, function (index, value) {
console.log(value);
});
});

var data={
"data":[
{
"outputQty":"2",
"orderSummaries":[],
"categoryName":"test",
"itemId":1,
"recipes":[],
"name":"Laddu"
},
{
"outputQty":"2",
"orderSummaries":[],
"categoryName":"Badam Pista Mundiri",
"itemId":2,
"recipes":[],
"name":"Barpi"
}
]
}
$.each(data.data, function (index, value) {
var tr='<tr>';
tr+='<td>'+value.outputQty+'</td>'+
'<td>'+value.categoryName+'</td>'+
'<td>'+value.itemId+'</td>'+
'<td>'+value.name+'</td>'+
'</tr>';
$('table').append(tr);
});
&#13;
td{
border:1px solid grey;
}
&#13;
答案 1 :(得分:2)
只需枚举response.data
$.ajax({
type: "GET",
url: "http://tomcatworkbench.com/Catering2/secured/getAllItems",
dataType: "json",
success: function(response) {
response.data.forEach(function(item) {
console.log(item.categoryName);
});
var firstItem = response.data[0];
console.log(firstItem.categoryName);
var allCategoryNames = response.data.map(function(item) {
return item.categoryName;
});
console.log(allCategoryNames);
var allCategoryFirstNames = response.data.map(function(item) {
return item.categoryName.split(' ')[0];
});
console.log(allCategoryFirstNames);
}
});
答案 2 :(得分:1)
您可以尝试以下示例。
var response = {"data":[{"outputQty":"2","orderSummaries":[],"categoryName":"test","itemId":1,"recipes":[],"name":"Laddu"},{"outputQty":"2","orderSummaries":[],"categoryName":"Badam Pista Mundiri","itemId":2,"recipes":[],"name":"Barpi"}]};
var data = response.data;
$.each(data,function(i,v){
for(var key in v){
if(key==="categoryName"){
console.log(i+". "+key+": "+v[key]);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>