且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript的DOM错误

更新时间:2023-12-05 15:01:10

这是您的代码的工作版本,建立一个列表。比较你的版本,看看你在哪里犯了错误,在标记和代码。

第二个错误的来源是传递给addBooks函数的错误数据(很可能为空),因此您必须修复该错误。



Chrome和Firebug具有优秀的带有断点的JavaScript调试器,因此可以利用它来确定问题:

http://jsfiddle.net/tgth2/



编辑:

你的问题在你对这个问题的评论和更新之后闪闪发光:


  1. 您的第一页正在从服务中加载JSON数据,但接着是 window.location.replace(Page2 Updated.html); ,它将浏览器发送到新页面(请注意,您之后立即调用 addBooks(data); ),但该代码从未执行,因为浏览器已经转到另一页

  2. 您的第二页在其中包含< body onload =addBooks();> ,这将导致函数成为用 null 数据调用,这是你的问题的原因。

解决方案:

数量o ne建议开始使用jQuery来处理你正在做的其他事情,而不仅仅是为AJAX调用。

第二,你应该有ajax调用和结果呈现在一个页面中,因为将浏览器重定向到另一个页面没有任何意义。因为您的JavaScript始终在单个页面的上下文中工作。只要你做了像 window.location.replace(..)之类的东西,你最终会失去在当前页面中所做的一切。

如果您进行这些更改,您会看到您的列表加载得很好!


this is my javascript code , I am trying to create a dynamic list in HTML with data I recieve from the server , The data is of type "json"

My Javascript snippet

function addBooks(data) { // USing DOM to populate the tables 


    //var  newdata=document.getElementById('addBooks');
    //newdata.setattribute()

    //get the unordered list

    var newdata = document.getElementById('addBooks');
    var parent = document.getElementById('gBookList');
    //removeChildrenFromNode(parent);

    //create list divider
    var listdiv = document.createElement('li');
    listdiv.setAttribute('id', 'gBookListDiv');
    listdiv.innerHTML = ("Books Found:");
    parent.appendChild(listdiv);
    // (this is where the first error happens)

    //create dynamic list

    for (i = 0; i < data.length; i++) {
        // (this is where the second error happens)



        //create each list item 
        var listItem = document.createElement('li');
        listItem.setAttribute('id', 'gBookListItem');
        parent.appendChild(listItem);
        //var link = document.createElement('a');
        //link.setAttribute('onclick','displayBook(data[i])');
        //link.setAttribute('href','#FindBook)');
        //listItem.appendChild(link);
        var pic = document.createElement('img');
        pic.setAttribute('src', data[i].pictureURL);
        pic.setAttribute('width', '80px');
        pic.setAttribute('height', '100px');
        pic.setAttribute('style', 'padding-left: 10px');
        link.appendChild(pic);
        var brk = document.createElement('br')
        link.appendChild(brk);
        var title = document.createElement('p');
        title.innerHTML = data[i].title;
        title.setAttribute = ('style', 'float:right');
        link.appendChild(title);
        var author = document.createElement('p');
        author.innerHTML = data[i].author;
        link.appendChild(author);
    }
    var list = document.getElementById('gBookList');
    // $(list).listview("refresh");
}

/*function removeChildrenFromNode(node){
            while (node.hasChildNodes()){
                node.removeChild(node.firstChild);
            }
        //}*/

My html code is

<!DOCTYPE html>

<head>
   <script ...> 
 <head>                  
<body onLoad="addBooks()">
    <div id="addBooks" class="row-fluid">
        <div id="gBookList">
        </div>
    </div>
</body>
</html>

I keep getting the following error which prevents me from populating the list , I am using chrome

1) Uncaught TypeError: Cannot call method 'appendChild' of null
2) Uncaught TypeError: Cannot read property 'length' of undefined

I do not understand why this should happen as the .length commands returns the correct integer ( amount of json objects) when I debug using a alert box .

the function that calls it

$.ajax({
    type: 'GET',
    url: ........,
    dataType: "json",
    complete: function (xhr, statusText) {
        alert(xhr.status);
    },
    success: function (data, textStatus, jqXHR) {
        alert(JSON.stringify(data));
        window.location.replace("Page2_updated.html");
        addBooks(data); // Passing JSON to be replaced on page
    },

    function (data, textStatus, jqXHR) {
        alert(data);
        alert('error');
    },

});

Edit

I changed my HTML file to the following structure after advice on this forum

<html>
<head>
</head>
<body>
<div id="1" "display:block">
</div>
<div id="2" "display:none">  // no onLoad() anymore!!
</div>
</body>
</html>

I have edited this part int he calling function

 $.ajax({
        type: 'GET',
        url: ........,
        dataType: "json",
        complete: function (xhr, statusText) {
            alert(xhr.status);
        },
        success: function (data, textStatus, jqXHR) {
            alert(JSON.stringify(data));
            if(document.getElementById(1).style.display == "block"){ 
                document.getElementById(1).style.display = "none"; 
                document.getElementById(2).style.display = "block"; }
            addBooks(data); // Passing JSON to be replaced on page
        },

        function (data, textStatus, jqXHR) {
            alert(data);
            alert('error');
        },
    });

But I still get the following errors Uncaught TypeError: Cannot call method 'appendChild' of null Uncaught TypeError: Cannot read property 'length' of undefined

Here is a working version of your code that builds a list. Compare with your version to see where you made the mistakes, in both mark up and code.

The source of your second error is incorrect data (most likely null) being passed to the addBooks function, so you would have to fix that.

Chrome and Firebug have excellent JavaScript debuggers with breakpoints, so use that to your advantage to identify the issues:

http://jsfiddle.net/tgth2/

EDIT:

Your problem is gleamingly obvious, after your comments and updates to the question:

  1. Your first page is loading the JSON data from the service, but then does window.location.replace("Page2 Updated.html");, which sends the browser to the new page (notice that you're calling addBooks(data); immediately after. But that code is never executed because browser has already gone to another page
  2. Your second page has <body onload="addBooks();"> in it, which will cause the function to be called with a null data. This is the cause of your problem.

SOLUTION:

Number one suggestion would be to start using jQuery for everything else you're doing, and not just for the AJAX call.

Secondly, you should have the ajax call and the results rendering in one page, as it does not make any sense to redirect the browser to another page. Because your javascript always works in the context of a single page. As soon as you do something like window.location.replace(..) you end up losing everything you've done in the current page.

If you make these changes, you will see that your list loads just fine!