如何在我的表单中使用AJAX

时间:2017-11-19 01:05:44

标签: php jquery ajax

我试图了解如何使用AJAX将两个数组发送到我的php脚本,最初我只是允许页面重新加载。

我已经开始实现AJAX调用但是我对如何发送两个数组感到困惑。我将如何使用我的PHP文件中的数据。这就是我到目前为止所做的:

<head>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>

<form method="post" action="submit.php" >

<input id="name" type="text" name="name[]" class=""/>
<input id="amount" type="text" name="amount[]" class=""/>

<button type="submit"  class="btn btn-primary btn-lg btn-block sendTheForm" name="sending" >Submit</button>

</form>

<script>

$(document).on('click', '.sendTheForm', function(){  

    $.ajax({  
       url:"submit.php",  
       method:"POST",  
       data:{},  
       success:function(data){

            swal({
               title: "Submitted",
               text: "sucessfully sent",
               icon: "success",
            });

        }  
     });  
  }

});
</script>

对此的任何帮助将不胜感激,希望我能学到一两件事!

2 个答案:

答案 0 :(得分:0)

var nameArrays = [];
function getArray(){
var inputs = document.querySelectorAll("#form input[name='name[]']");
for(var i=0; i<inputs.length; i++)
nameArrays.push(inputs[i].value)
console.log(nameArrays)
}
<form id="form">
<input type="text" name="name[]" value="Name1" /> 
<input type="text" name="name[]" value="Name2" /> 
<input type="button" onclick="getArray()" />
</form>

var array1 = ['a','b', 'c'],
array2 = ['d', 'e', 'e'];

$(document).on('click', '.sendTheForm', function(){  

        $.ajax({  
             url:"submit.php",  
             method:"POST",  
             data:{ array1 : array1, array2: array2},  
             success:function(data){

                swal({
                    title: "Submitted",
                    text: "sucessfully sent",
                    icon: "success",
                });

             }  
        });  
   }

 });

聚苯乙烯。如果您要将表单数据发送为JSON,则可以使用Jquery serialize之类的

 $.ajax({  
             url:"submit.php",  
             method:"POST",  
             data: $("#formId").serialize(),  
             success:function(data){}
})

答案 1 :(得分:0)

使用jquery,在$.ajax来电时,请尝试使用serialize()。详细了解serializeserializeArray

       $.ajax({  
             url:"submit.php",  
             method:"POST",  
             data: $("form").serialize(),
             contentType: "application/json; charset=utf-8",
             dataType: 'json',
             success:function(data){
             // do what you want to do after ajax success
             }  
        }); 
相关问题