如何使用 ajax 将文本输入字段附加到表单,而不会丢失用户对表单的输入


How do I append a text input field to a form using ajax without losing user input on the form?

我一直在互联网和StackOverflow上寻找解决方案,但我还没有想出一个。我有一个表格要开始:

<div class="container_12">
<div id="masthead" class="grid_12">
<br/><h1>Form Builder</h1>      
</div>
<div id="main-content" class="grid_8" style="margin-top:-5px">
    <form action="" id="form" name="form">
        <div id="formbuilder" name="formbuilder">
        <label>Question:</label><input type="text" name="question1" id="question1"/><br/>
        </div>
        <button type="button" onClick="loadXMLDoc()">Add New Question</button>
        <input type="submit" name="submit" id="submit"/>
    </form>
</div>
<div id="sidebar" class="grid_4">
</div>

当按下"添加新问题"按钮时,它执行了以下javascript:

    var count = 1; //only executed once on the initial load.
function loadXMLDoc() //executed every time the button is pressed.
{
    count++;
    var xmlhttp;
    if(window.XMLHttpRequest)
    {//code for anything better than IE6
    xmlhttp=new XMLHttpRequest();
    }
    else
    {//IE6 or lower
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("formbuilder").innerHTML += xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "question.php?c=" + count, true);
    xmlhttp.send();
}

该 javascript 反过来从 question.php 中获取一个新的输入字段,这是一个非常简单的 php 脚本:

   <?
    echo '<label>Question:</label><input type="text" name="question'.$_GET['c'].'" id="question'.$_GET['c'].'"/><br/>';
   ?>

现在,乍一看一切正常。当我按下按钮时,会生成一个新的问题字段并将其附加到表单中。但是,如果我在按下按钮之前在任何问题文本框中有任何值,则所有数据都会消失,即使直观地认为情况并非如此。为了增加乐趣,这只发生在Chrome和Firefox中。出于某种原因,Internet Explorer 9 按预期工作。

显然我做错了什么,但我无法弄清楚它可能是什么。我已经有一段时间没有使用 AJAX 了,非常感谢这方面的任何帮助。谢谢!

至少可以在Chrome和Firefox中使用insertAdjacentHTML,而不是使用innerHTML。

document.getElementById("formbuilder").insertAdjacentHTML("beforeend", xmlhttp.responseText)

从这个MDN页面阅读更多关于它的信息。