信息显示在控制台中,但不在HTML中

时间:2018-04-22 22:25:38

标签: javascript json

晚上好,

我已经和它斗争了2天。请帮忙!!我还在学习,而且我已经学习了JSON对象和AJAX。我设法让名字显示在控制台中。但是,它并没有出现在div中。我应该使用appendChild()将它注入DOM吗?

简单的JSON:

{
  "Instructors" : [

  {
  "full_name" : "Ray Villalobos",
  "title" : "Staff Author",
  "links" : [
        { "blog"     : "http://iviewsource.com" },
        { "facebook" : "http://facebook.com/iviewsource" },
        { "podcast"  : "http://feeds.feedburner.com/authoredcontent" },
        { "twitter"  : "http://twitter.com/planetoftheweb" },
        { "youtube"  : "http://www.youtube.com/planetoftheweb" }
    ]
   },

   {
     "full_name" : "Quincy Adams",
     "title" : "Mega Author",
     "links" : [
        { "blog"     : "http://getoffmytip.com" },
        { "facebook" : "http://facebook.com/getoffmytip" },
        { "podcast"  : "http://feeds.feedburner.com/getoffmytip" },
        { "twitter"  : "http://twitter.com/surpassedgoddess" },
        { "youtube"  : "http://www.youtube.com/surpassedgoddess" }
        ]
    }
       ]
    }

的script.js:

$(function() {
function getData() {

var request;
if (window.XMLHttpRequest) {
    request=new XMLHttpRequest();
} else {
    request=new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'data.json');
request.onreadystatechange = function() {
    if ((request.status === 200) &&
        (request.readyState === 4)) {

        var info = JSON.parse(request.responseText); 

        var author = '';
        for (var i = 0; i <= info.Instructors.length-1; i++) {
            for (key in info.Instructors[i]) {
                if (info.Instructors[i].hasOwnProperty(key)) {

        }//for hasOwnProperty

            }//for each object
            author += '<p>' + info.Instructors[i].full_name + '</p>';
        }//for each array element
        document.getElementsByClassName('div1').innerHTML = author;
        console.log(author);
} //ready
} //event
request.send();
}//getData  
window.addEventListener("load", getData);

});

1 个答案:

答案 0 :(得分:0)

你几乎有问题在这里document.getElementsByClassName('div1')

document.getElementsByClassName('div1')为您提供所有具有您提到的班级名称的div的列表。如果只有一个div,它仍然会返回一个包含该节点的列表。您应该做的是使用document.getElementsByClassName('div1')[0]访问该节点(如果您想要将第一个div附加到第一个div,或者只有一个div包含类div1)。

PS。您不想一次又一次地扫描所有DOM以找到该节点,因此您最好在for循环之外获取该引用,然后附加html或您想要的任何内容。

注意

你应该使用document.querySelector('selector')因为当你有复杂的选择器时它会相对更强大和有用。

PS。 querySelectorAllgetElementsByClassName:返回值不同。 querySelectorAll将返回静态集合,而getElementsByClassName将返回实时集合。