admin管理员组

文章数量:1317909

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.responseText;
    //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';  
    }

}

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.responseText;
    //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';  
    }

}
Share Improve this question asked May 7, 2010 at 6:32 VijayVijay 5,43310 gold badges56 silver badges88 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

A few ments:

  • 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 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.

本文标签: