JSON Data and Manipulating the Content

て烟熏妆下的殇ゞ 提交于 2019-12-11 17:53:23

问题


I am trying to write out the data from this JSON url into li's.

The JSON link is https://www.inquicker.com/facility/americas-family-doctors.json

    <!DOCTYPE html>
    <html>
    <head>
    <title>JQuery (cross-domain) JSONP</title>
    <script  type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js">    </script>
    <script>
$(document).ready(function(){
    $.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json', 
        function(data){ 
        alert(data.facility);
        $.each(data.schedules, function(i, name){
            $('#names').append('<li>' + name.available_times[0] + '</li>');
        });
    });
});
    </script>
    </head>
    <body>
    <ul id="names"></ul>
    </body>
    </html>

回答1:


I have created a JSFidle check this. You to check the data is available in available_times then proceed. if (name.available_times.length){....... ..... ....

$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
    function(data){

    $.each(data.schedules, function(i, name){
        times=''
            if (name.available_times.length){
                times='<ul>'
                times+='<li><a href="'+name.available_times[0].url+'">'+name.available_times[0].when+'</a></li>'
                times+='</ul>'
            }
            else{
               times='<ul><li>No Time Available</li></ul>'                    
            }
        $('#names').append('<li>' + (name.name) + times + '</li>');
    });
});

});




回答2:


You can add a test to check if the length of available_times array is > 0 before accessing the first cell.

And then, you can access to when or url properties :

  • available_times[0].when
  • available_times[0].url

Edit : save name.available_times[0] in a temp var and write temp.when or temp.url.




回答3:


In the JSON link, some schedules have empty available_times arrays.

And available_times[0] is an object that contains the properties when and url, so you'll have to write name.available_times[0].url



来源:https://stackoverflow.com/questions/13817976/json-data-and-manipulating-the-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!