Javascript的DOM错误 [英] Javascript DOM errors

查看:120
本文介绍了Javascript的DOM错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的javascript代码,我试图用服务器接收的数据在HTML中创建一个动态列表,数据是json类型的数据

我的JavaScript片段

  function addBooks(data){//使用DOM填充表格


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

//获取无序列表

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

//创建列表分隔符
var listdiv = document.createElement('li');
listdiv.setAttribute('id','gBookListDiv');
listdiv.innerHTML =(找到的书:);
parent.appendChild(listdiv);
//(这是发生第一个错误的地方)

//创建动态列表

(i = 0; i< data.length; i ++ ){
//(这是发生第二个错误的地方)



//创建每个列表项目
var listItem = document.createElement( '礼');
listItem.setAttribute('id','gBookListItem');
parent.appendChild(listItem);
// var link = document.createElement('a');
//link.setAttribute('onclick','displayBook(data[i])');
//link.setAttribute('href','#FindBook)');
//listItem.appendChild(链接);
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);
}
//} * /

我的html代码是

 <!DOCTYPE html> 

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

我不断收到以下错误,它阻止我填充列表,我正在使用chrome



1)Uncaught TypeError:无法调用null的方法'appendChild'

2)Uncaught TypeError:无法读取未定义的属性'length'

我不明白为什么会发生这种情况,因为使用警告框进行调试时,.length命令会返回正确的整数(json对象的数量)。



调用它的函数

  $。ajax({
类型:'GET',
url:........,
dataType:json,
完成:function(xhr,statusText){
alert(xhr.status);
},
success:function(data,textStatus,jqXHR){
alert(JSON.stringify(data));
window.location .replace(Page2_updated.html);
addBooks(data); //传递JSON以替换页面


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







我将HTML文件更改为以下结构在这个论坛上的建议

 < html> 
< head>
< / head>
< body>
< div id =1display:block>
< / div>
< div id =2display:none> //不再有onLoad()了!
< / div>
< / body>
< / html>

我编辑过这部分int他调用函数

  $ .ajax({
类型:'GET',
url:........,
dataType:json ,
complete:function(xhr,statusText){
alert(xhr.status);
},
success:function(data,textStatus,jqXHR){$ b $ (1).batch(JSON.stringify(data)); none;
document.getElementById(2).style.display =block;}
addBooks(data); //传递JSON以替换页面
},

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

但我仍然收到以下错误
Uncaught TypeError:无法调用方法'appendChild' null
Uncaught TypeError:无法读取未定义的属性'length'

解决方案

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

第二个错误的来源是传递给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!

这篇关于Javascript的DOM错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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