开发者

How to resolve "Could not convert JavaScript argument arg 0 [nsIDOMHTMLDivElement.appendChild]" error

开发者 https://www.devze.com 2022-12-29 05:43 出处:网络
i have a json object returned from ajax and when i alert it, it is displayed correctly and i try to add those into a unordered list and add that to a place holder div, but throws the above error..

i have a json object returned from ajax and when i alert it, it is displayed correctly and i try to add those into a unordered list and add that to a place holder div, but throws the above error..

function handleResponse() {
  if(httpa.readyState == 4){
  var response = httpa.responseT开发者_开发百科ext;
    //alert(response);
    if(response!='empty')
    {
      //alert(response);
      eval("prod="+response);
      var len = prod.length;
      var st = "<ul>";
      for(var cnt=0;cnt<len;cnt++)
      {
        st = st + "<li onclick='set("+prod[cnt].id+")'>"+prod[cnt].name+"</li>";  
      }      
      st = st + "</ul>";
      }
      var tt = document.getElementById('holder1');
      tt.appendChild(st); // i even tried **tt.appendChild(eval(st));**
      tt.style.display = 'block';  
    }

}


A few comments:

  • eval("prod="+response); - don't do that. It's creates a global 'prod' variable, can execute arbitrary code, prevents the JS engine from speeding up your code, and generally is considered a bad coding practice.
    • Use a JSON parser instead (either from json.org or helpers from your favorite library).
  • tt.appendChild(st); // i even tried **tt.appendChild(eval(st));** - appendChild takes a DOM node; st is a string and eval(st) evaluates st assuming it contains JavaScript code (so running it on XML will result in a syntax error, unless you're using E4X, which still wouldn't create an object suitable for use with appendChild).
    • You should either parse the HTML code you've built (via innerHTML, createDocumentFragment, or -- again -- using a helper from your favorite JS library)
  • Finally, if you do this a lot, consider using templates instead.


tt.innerHTML += st;

As st is a string, not a DOM element.

0

精彩评论

暂无评论...
验证码 换一张
取 消