gpt4 book ai didi

javascript - 如何使用 ajax 将文本输入字段附加到表单而不丢失表单上的用户输入?

转载 作者:行者123 更新时间:2023-11-28 01:51:27 26 4
gpt4 key购买 nike

我一直在互联网和 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 page了解更多信息.

关于javascript - 如何使用 ajax 将文本输入字段附加到表单而不丢失表单上的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19643401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com