AJAX如何创建新元素?

时间:2014-01-14 13:28:17

标签: html ajax asp-classic

我一直在使用在线教程,介绍如何使用ajax创建一个依赖于用户输入的新元素。目前,它所要做的只是替换已经制作的div的innerhtml,但是我想创建一个新的div并用用户指定的输入填充它。这是我目前的代码:

AJAX:

  <script>
     function showType(str)
     {
     if (str=="")
       {
       document.getElementById("Answer").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==200)
         {
           document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

         }
       }
     xmlhttp.open("GET","/ASPScripts/QuestionDesign.asp?q="+str,true);
     xmlhttp.send();
     }
  </script>

ASP

<%
 response.expires=-1
dim q
q=request.querystring("q")

response.write("<input type='" & q & "'/>")
 %>

关于如何做到这一点的任何想法?我知道它可能是一个非常简单的答案,我只是对这个东西很陌生

1 个答案:

答案 0 :(得分:0)

基本上,你要问的是如何将新元素附加到DOM:

var newDiv = document.createElement("div");

newDiv.innherHtml = xmlhttp.responseText;

document.getElementById("newDivParent").appendChild(newDiv);

编辑:您可以在此页面的控制台(Chrome中的f12)中粘贴此代码以查看其工作原理:

 var newDiv = document.createElement("div");

 newDiv.setAttribute('style', 'position:fixed; top:0; left:0; right:0; bottom:0; z-   index:10000000;     background-color:red;' )

 document.body.appendChild(newDiv);