javascript - 如何使用 jQuery Ajax 成功在我的 html 上打印邮递员返回的 JSON 数组?
问题描述
我希望循环通过我的 API 返回的 JSON 数组[{"a":1},{"b":2},{"c":3},{"d":4}]
。如何将 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>
解决方案
您正在遍历数组,函数将参数作为item
and index
:
$.each(array, function(index,item){});
进行二次循环并遍历对象:
$.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>
推荐阅读
- python - 如何在“ascii”编解码器中编码字符“\xa0”
- java - 绝对定位 Swing(Java)不起作用
- imagemagick - 使用 ImageMagick 和 CloudConvert 调整图像大小
- html - Facebook、Twitter 图标请取消注释以获取链接
- java - 在 kotlin 中为功能接口抛出异常
- asp.net-core - 页面和操作明智的授权 Asp.Net Core Razor 页面
- bitmap - PPM 格式是行业标准吗?
- html - 为什么前缀 data-* 在 Angular 9 中不起作用?
- javascript - JavaScript:在带有链接的按钮上播放音频
- java - 在 Docker Swarm 中运行集群时暴露 Nifi UI