首页 > 解决方案 > 如何使用 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>

标签: javascriptjqueryhtmljsonajax

解决方案


您正在遍历数组,函数将参数作为itemand 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>


推荐阅读