[英]How do I print my postman returned JSON array on my html using jQuery Ajax success?
I wish to loop through my JSON array returned by my API [{"a":1},{"b":2},{"c":3},{"d":4}]
.我希望遍历我的 API [{"a":1},{"b":2},{"c":3},{"d":4}]
返回的 JSON 数组。 How do parse the JSON key and value onto my html so the output div gives only the key and value.如何将 JSON 键和值解析到我的 html 上,以便输出 div 仅提供键和值。
<body>
<div id = "result" style = "color:green" ></div>
<script type = "text/javascript">
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/api/",
type: 'GET',
dataType: 'json',
success: function(res) {
console.log(res);
//var data=$.parseJSON(res);
//var data = JSON.stringify(res)
$.each(res, function(key, value) {
console.log(key);
console.log(value);
var para = document.createElement("P");
para.innerHTML = key + ":" + value;
document.getElementById("result").appendChild(para);
})
}
});
})
</script>
</body>
You are looping through array ,function will take arguments as item
and index
:您正在遍历数组,函数将参数作为item
和index
:
$.each(array, function(index,item){});
Make a secondary loop and iterate through objects:进行二次循环并遍历对象:
$.each(object, function(key,value){});
res = [{ "a": 1 }, { "b": 2 }, { "c": 3 }, { "d": 4 }] $.each(res, function(index,item) { $.each(item, function(key,value){ var para = document.createElement("P"); para.innerHTML = key + ":" + value; document.body.appendChild(para); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Your JSON format is an array, with each key an object您的 JSON 格式是一个数组,每个键都是一个对象
[
{"a" : 1},
{"b" : 2},
{"c" : 3},
{"d" : 4}
]
So this means that when you loop through the items, the key
will be the index of the array, and the value
will be the object所以这意味着当你遍历项目时, key
将是数组的索引, value
将是对象
$.each(res, function(key, value) {
console.log(key); // -> will be 0, 1, 2 etc
console.log(value); // -> will be {"a" : 1}, {"b" : 2}, etc
});
So there are 2 options, you can either change your API to return a single object with the key:value pairs like this因此有 2 个选项,您可以更改 API 以返回具有键值对的单个对象,如下所示
{
"a" : 1,
"b" : 2,
"c" : 3,
"d" : 4
}
Or you need to add an extra loop in your code, so that you can loop through the objects and display the values (although I would recommend to rather go with the first option或者您需要在代码中添加一个额外的循环,以便您可以遍历对象并显示值(尽管我建议您宁可使用第一个选项
$.ajax({
url: "http://localhost:8080/api/",
type: 'GET',
dataType: 'json',
success: function(res) {
$.each(res, function(key, object) {
$.each(object, function(key, value) {
var para = document.createElement("P");
para.innerHTML = key+ ":" +value;
document.getElementById("result").appendChild(para);
});
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.