繁体   English   中英

如何使用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了,希望对此有所帮助。 谢谢!

除了可以使用innerHTML之外,还可以至少在Chrome和Firefox中使用insertAdjacentHTML。

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

从此MDN页面中了解更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM