My JavaScript code is supposed to receive data using AJAX and display it in a DIV called "txtHint". However, this is the error I get when the code executes (I am using the build-in debugger in Safari):
TypeError: Result of expression 'document.getElementById("txtHint")' [null] is not an object.
Here is the code:
function showItem(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status开发者_如何学C==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getitem.php?q="+str,true);
xmlhttp.send();
}
Now i get: TypeError: Result of expression 'el' [undefined] is not an object.
Does this mean my element does not exist?
First, check if the element exists.
var el = document.getElementById('txtHint');
if ( el ) {  
   el.innerHTML = xmlhttp.responseText;
}
Make sure you are binding this after the element has been generated in the DOM. You can also wait for the entire window to load via window.onload = showItem.
People use frameworks like jQuery to save time. Your code would result in something as succinct as:
$(function() {
   function blah(str) {
      if ( str == '' ) {
        $('#txtHint').html('')
        return;
      }
      $.ajax({ url:'blah.php', success:function(html) {
        $('#txtHint').html(html);
      } })
   }
});
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论