JavaScript:如何在AJAX调用中使用jQuery遍历JSON对象 [英] JavaScript: How to Loop through JSON objects with jQuery in an AJAX call

查看:79
本文介绍了JavaScript:如何在AJAX调用中使用jQuery遍历JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试学习这个概念时遇到了困难.

I am having difficulty trying to learn this concept.

我有一个JSON文件,其中列出了医院,其地址,时间和电话.

I have a JSON file with a list of hospitals, their address, hours and phone.

我想从JSON数据进行AJAX调用并将数据列出到屏幕上.

I want to make an AJAX call from JSON data and list the data onto the screen.

当我尝试仅列出地址列表时,我只能列出第一家医院.

I can only get the first hospital to list, when I try to list the address only the address lists.

如何使用列出对象及其属性的循环来编写此代码?

How can I write this using a loop that will list the objects and their properties?

有人可以向我解释一下吗?

Can someone explain this to me, please?

请帮助-预先谢谢您.

JSON-

https://api.myjson.com/bins/b29r7

JS-

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
    url: url,
    method: 'GET',
}).done(function(result){
    var data = result.surrey;
    for(var i=0; i<data.length; i++){
        $('#data').each(function(index, ele){
            $(ele).html(data[index].hospital);
        });
    }
}).fail(function(err){
    throw err;
});

HTML-

<p id="data"></p>

推荐答案

这是一个有效的示例:

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
  url: url,
  method: 'GET',
}).done(function(result) {
  // JSON data array
  var data = result.surrey;

  // get DOM node to be parent of child list nodes
  var $data = $('#data');

  // iterate through each object in JSON array
  data.forEach(function(item) {

    // create an unordered list node
    var $ul = $('<ul></ul>');

    // iterate through all the properties of current JSON object
    for (var field in item) {

      // append list item node to list node
      $ul.append(`<li>${field}: ${item[field]}</li>`);
    }

    // append list node to parent node
    $data.append($ul);
  });
}).fail(function(error) {
  console.error(error);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="data"></div>

JSFiddle演示: https://jsfiddle.net/L6j8n17j/4/

JSFiddle Demo: https://jsfiddle.net/L6j8n17j/4/

这篇关于JavaScript:如何在AJAX调用中使用jQuery遍历JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆