jquery - 使用循环在 HTML 中显示来自 jQuery.ajax 的 json 数据

标签 jquery html json ajax

你好,假设我有以下 ajax 调用:

jQuery.ajax({
    type: "GET",
    url: "https://myurl.com",
    success: function(data)
    {
        console.log(data);
    }
});

这会产生以下 json 数据(在我的控制台中)

{
  "meta": {
    "last_updated": "2017-07-06"
  },
  "results": [
    {
      "term": "DRUG INEFFECTIVE",
      "count": 1569
    },
    {
      "term": "NAUSEA",
      "count": 1374
    },
    {
      "term": "FATIGUE",
      "count": 1371
    }
  ]
}

我如何在我的 HTML 页面中使用此数据填充 div,格式如下:

term: x
count: xx

term: x
count: xx

term: x
count: xx

我对“元”东西不感兴趣,只对“结果”感兴趣

有人知道如何使用简单的循环来显示这些数据吗?

谢谢!

最佳答案

您可以在“成功函数”中循环遍历 data.results,如下所示:

jQuery.ajax({
    type: "GET",
    url: "https://myurl.com",
    success: function(data)
    {
        console.log(data);

        jQuery.each(data.results, function(i, val) {
            // here you can do your magic
            $("#yourdivid").append(document.createTextNode(val.term));
            $("#yourdivid").append(document.createTextNode(val.count));
        });
    }
});

关于jquery - 使用循环在 HTML 中显示来自 jQuery.ajax 的 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134555/

相关文章:

html - 具有更多文本的元素会下推其他行内 block 元素。为什么?

javascript - 如何使用json读取html中的php数据

javascript - 将 JSON 字符串转换为 JavaScript 对象以进行迭代

iphone - 从 JSON 在 Devise 中创建用户

javascript - 当我们单击特定选项卡时,如何隐藏 Accordion 菜单项中打开的所有选项卡?

javascript - 覆盖可点击的div

javascript - 如何为 ASP.NET MVC 4 和 ASP.NET Web API 实现单独的项目

javascript - 使用复选框隐藏和显示元素

javascript - 强制浏览器重绘图像

javascript - 如何使用requirejs加载papa解析js文件?