【问题标题】:How to submit a form with multiple fields having a same name attribute using ajax?如何使用ajax提交具有相同名称属性的多个字段的表单?
【发布时间】:2018-10-17 14:20:06
【问题描述】:

我有一个 HTML 表单

<html>
<head></head>
<form>
     <input type="text" name="question[]" />
     <input type="text" name="question[]" />
     <input type="file" name="image" />
     <input type="submit" name="save" /> 
</form>
</html>

现在用 ajax 提交表单 我有 ajax 代码,但它不工作。它只得到一个值。

$("#submit").click(function() { 
    var que_id  = $("input[type='text'][name='question[]']").val();
    $.ajax({
       type: "POST", 
       url:  "action.php",
       data: {"que_id": que_id},
       success: function(result) {
       $("#question_wrap").html(result);
    }
  });
});

我该怎么做?

【问题讨论】:

标签: javascript php jquery html ajax


【解决方案1】:

使用 ajax 将表单数据发送到 php 文件

  1. 将 enctype 添加到您的表单中

    <form id="questionForm" action="" method="post" enctype="multipart/form-data">
        <input type="text" name="question[]" />
        <input type="text" name="question[]" />
        <input type="file" name="image" />
        <input type="submit" name="save" />
    </form>
    
  2. 使用序列化将表单数据传递给 php 文件

    $.ajax({
     url: 'action.php',
     data: $("#questionForm").serialize(),
     method: "post",
     success: function (result) {
             $("#question_wrap").html(result);
           }
    });
    
  3. 使用字段名访问 PHP 文件中的表单值

    <?php 
       foreach($_POST['question'] as $key => $value){
             // your logic
       }
      $filedata= $_FILES['image'];
    ?>
    

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 2023-03-25
    • 2011-01-13
    • 2016-06-02
    • 1970-01-01
    • 2020-11-03
    • 2021-12-19
    • 2016-09-28
    • 2011-01-18
    相关资源
    最近更新 更多