通过javascript进行DOM更新无法正常工作

时间:2016-10-07 06:17:44

标签: javascript html ajax dom innerhtml

我只是想尝试使用javascript来创建一个简单的功能用于学习目的,但<p>标记内的内容没有更新,我在这一点上陷入困​​境。我的代码如下:

&#13;
&#13;
<!DOCTYPE html>
<html>
	<head>
		<title> Ajax Search Box </title>
		<script>
			function LoadList()
			{
				var searchBox =  document.getElementById("txtSearch");
				var resultBox =  document.getElementById("results");
				var searchedChars = "";
				var xHttp = new XMLHttpRequest();
				searchedChars += searchBox.value;
				xHttp.onreadystatechange = function(){
					if(this.readyState == 4 && this.status == 200)
					{
						var xmlContent = this.responseXML;
						var nameList = xmlContent.getElementsByTagName("name");
						var dispText = "";
						for(var i = 0 ; i < nameList.length ; i++)
						{
							dispText += nameList[i].textContent + "<br/>";
						}
						resultBox.innerHtml = dispText;
					}
				};
				xHttp.open("GET","AssessorList.xml",true);
				xHttp.send();
			}
		</script>
	</head>
	<body>
		<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
		<p id="results">
			No Data Available.
		</p>
		
	</body>
</html>
&#13;
&#13;
&#13;

有人能告诉我为什么innerHtml没有更新?提前谢谢。

P.S:代码是从xml文件中获取数据,正如我在浏览器控制台中看到的那样,值被传递给dispText变量。

1 个答案:

答案 0 :(得分:1)

 <!DOCTYPE html>    
 <html>     
 <body> 
 <input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />               
 <p id="results">No data available</p> 
     <script> 
     function LoadList() {   
        var xhttp = new
        XMLHttpRequest();   
        var searchBox = 
        document.getElementById("txtSearch");
        var resultBox =  document.getElementById("results");
        var searchedChars = "";
        searchedChars += searchBox.value;   
        xhttp.onreadystatechange = function() {
         //alert(this.status);
        if (this.readyState == 4 && this.status == 200) {
         var xmlContent = this.responseXML;
                            var nameList = searchedChars;
                            alert(nameList);
                            var dispText = "";
                            for(var i = 0 ; i < nameList.length ; i++)
                            {
                                dispText += nameList[i] + "<br/>";
                            }
                            resultBox.innerHTML = dispText;
        }   
    };   
      xhttp.open("GET", "ajax.txt", true);   
      xhttp.send(); 
     } </script>    
    </body> 
  </html> 

希望这可以帮到你