具有未知数量变量的AJAX帖子

时间:2014-04-26 19:43:16

标签: javascript php jquery ajax

我的网站上有一张表格。问题存储在数据库中,一些变量确定您看到的问题。因此,问题的数量是未知的。问题的代码是这样的:

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发布这些问题的答案。如何用未知数量的问题做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以通过这样的ajax提交表单。

$("#myForm").submit(function() {
    $.post('post.php',$(this).serialize(), function(data) {
         alert(data);
    });

    return false;
});

答案 1 :(得分:1)

如前作者所说,使用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/

希望,这会有所帮助。

问我有什么不清楚的地方。

相关问题