我的网站上有一个表格。这些问题存储在数据库中,一些变量决定您看到哪些问题。因此,问题的数量是未知的。问题的代码是这样的:
HTML
<ol class="questions">
<?php
$number = 1;
while($row = mysql_fetch_assoc($result)) {
echo '<li>';
echo '<span><label for="q'.$number.'">'.$row['question'].'</label></span>';
echo '<input id="q'.$number.'" name="q'.$number.'" type="text" value="'.$row['description'].'" onclick="this.value="";this.onclick="test";this.style.color="#000000"; setAttribute("type", "text");" onfocus="if (this.value == "'.$row['description'].'") {this.value = ""; setAttribute("type", "text");}" onblur="if (this.value == "") {this.value = "'.$row['description'].'";setAttribute("type", "text");}"/>';
echo '</li>';
$number++;
};?>
</ol>
现在,在提交表单时,我想使用 AJAX 发布这些问题的答案。我该如何解决未知数量的问题?
最佳答案
正如之前的作者所说,使用 serialize()
函数。他没有提到我现在要澄清的事情。
JavaScript 代码:
$("#button").on("click", function() {
$.ajax({
url: "someurl.php",
method: "post",
data: $("#myform").serialize()
});
});
HTML 代码必须是这样的:
<form id="myForm">
<input type='text' name='field1' />
<input type='text' name='field2' />
<input type='text' name='etc' />
</form>
<a href='#' id="button">Send ajax</a>
现在,当您单击Send ajax
按钮时,表单将被序列化(这意味着创建字符串,其中将包含有效的 url 查询,因此可以随请求一起发送)。在这里阅读:https://api.jquery.com/serialize/
希望,这会有所帮助。
有什么不明白的可以问我。
关于javascript - 具有未知数量变量的 AJAX 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315693/