将输入数据作为数组传递给 jquery

To pass input data as array to jquery

我要求学生使用 foreach 回答问题(哪些问题从数据库中检索),我必须在所有答案都填满后传递给 jquery,然后传递给控制器​​并保存到数据库。

<div>
    <tbody>
        <?php foreach ($questions as $question) { ?>
        <tr>
            <td ><?php echo $question['id']; ?></td>
            <td> <?php echo $question['question']; ?> </td>
            <td><input type='text' name='name' required="required" class="form-control" placeholder='Enter Your Answer'></td>
            // this is answer field associated with each question
        </tr>
        <?php } ?>  
    </tbody> 
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" id ="next" type="button" >Next</button>

当学生填写所有答案时(问题答案)传递给 jquery 这是脚本

<script>
          $(document).ready(function($){
            $(".gg").click(function(){
            var array = $("input[name]").val();
            $.ajax({
          type: "POST",
          datatype:"json",
          url: BASE_URL+"student/info",
          data: 'data='+array,

          success: function(response) {


          }});

        return false;
    });  
});
        </script>    

当学生提交答案时,只有第一个答案传递给jquery函数,不能传递所有答案

数据格式不正确

data: {'data=': array_variable },

如果您想更好地发送所有表单数据,您可以将其序列化并将其发送到您的 php 端并序列化 there.Like:

data : $('#form').serialize()

ELSE 没有序列化

var textboxes = $('input[name="answer[]"]').val();
data : {'data':textboxes},

您需要动态给出输入文本框的名称

代码中

<div>
      <form name='question' id='question' >
        <tbody>
            <?php foreach ($questions as $question) { ?>
            <tr>
                <td ><?php echo $question['id']; ?></td>
                <td> <?php echo $question['question']; ?> </td>
                <td><input type='text' name='name[<?php echo $question["id"]; ?>]' required="required" class="form-control" placeholder='Enter Your Answer'></td>
                // this is answer field associated with each question
            </tr>
            <?php } ?>  
        </tbody> 
      </form>
    </div>
    <button class="btn btn-primary nextBtn btn-lg pull-right" id ="next" type="button" >Next</button>

在脚本中

<script>
$(document).ready(function($){
$("#id").click(function(){
    $.ajax({
        type: "POST",
        url: BASE_URL+"student/info",
        data: $('#question').serialize(),

        success: function(response) {


        }});

        return false;
      });  
});     
</script>