通过ajax

时间:2015-07-15 00:34:55

标签: javascript php jquery html ajax

我有下面的HTML,我的想法是我有一个添加按钮,你可以添加多个地址。添加按钮只是将html插入另一个具有相同名称的输入,从而创建一个html输入数组。我无法通过ajax将多个输入传递给php脚本。

<form id="addTripForm" class="form-horizontal">
<div class="form-group">
    <label class="col-xs-4 text-right">Address</label>
    <div class="col-xs-8"><input type="text" class="form-control" id="deliveryAddress[]" name="deliveryAddress[]" required/></div>
</div>
</form>

我尝试过这种传递值的方式(这里我只是按名称获取元素并将其放在变量formData中)。

var deliveryAddress = document.getElementsByName('deliveryAddress[]');
var formData = {"deliveryAddress":deliveryAddress};

通过以下方式,我获取元素,然后循环遍历它们并将这些值推送到数组,然后将该数组赋值给变量formData

var deliveryAddress = document.getElementsByName('deliveryAddress[]');
var deliveries = new Array();
for(var i=0;i<deliveryAddress.length;i++){
        deliveries.push(deliveryAddress[i].value);
}
var formData = {"deliveryAddress":deliveries};

然后我使用变量formData中的值(从上面开始)并通过ajax

推送它
$.ajax({
        url : "/admin/PHPClasses/addToDB.php?type=Trip",
        type: "POST",
        data : formData,
        success: function(data, textStatus, jqXHR)
        {
            $('.form-group').hide();
            $('.bg-success').show();
            $('#saveChanges').hide();
            window.location.reload();
         },
         error: function (jqXHR, textStatus, errorThrown)
         {
            $('.bg-danger').show();
         }
});

最后在我的PHP脚本中,我尝试按如下方式访问deliveryAddress

$deliveryAddress = filter_input(INPUT_POST, "deliveryAddress");

如果有人能够证明我做错了什么,也知道这是解决这个问题的最佳方法。非常感谢您的所有帮助。

  

更新:我认为所有答案都可能是正确的,我只是注意到我没有关闭页面底部的正文和html标签,这导致javascript序列化以某种方式无法正常工作。感谢大家的帮助

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

  

首先,您可以使用jQuery .serialize()

     

其次,使用 serialize()

更新您的ajax代码

Java脚本Ajax代码:

$(document).ready(function() {
    // form submit function
    $("#addTripForm").on("submit", function(e) {
        // stop form submission
        e.preventDefault();
        $.ajax({
            url: "/admin/PHPClasses/addToDB.php?type=Trip",
            type: "POST",
            data: $("#addTripForm").serialize(),
            success: function(data, textStatus, jqXHR) {
                $('.form-group').hide();
                $('.bg-success').show();
                $('#saveChanges').hide();
                //window.location.reload();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('.bg-danger').show();
            }
        });
    })
});
  

第三,使用下面的PHP代码来获取加法器

<?php
// filter user input
$deliveryAddress = filter_input(INPUT_POST, 'deliveryAddress', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
// join array with comma
$deliveryAddress = implode(",\n", $deliveryAddress);
// show address
echo $deliveryAddress;

这里是完整代码html js和php:

$(document).ready(function() {
    //maximum input boxes allowed
    var max_fields = 10;
    //Fields wrapper
    var wrapper = $(".pure-control-group");
    //initlal text box count
    var x = 1;
    //on add button click
    $('body').on("click", ".fa-plus-circle", function(e) {
        //max input box allowed
        if (x < max_fields) {
            //text box increment
            x++;
            //add input box
            var render = '<div class="pure-control-group"> ' + '  <label for="deliveryAddress[]">Address</label>' + '      <input name="deliveryAddress[]" type="text" placeholder="Address...">' + '      <i class="fa fa-plus-circle"></i> ' + '      <i class="fa fa-trash-o"></i>' + '</div>';
            $(wrapper).after(render);
        }
    });
    //on delete button click
    $('body').on("click", ".fa-trash-o", function(e) {
            //user click on remove text        
            $(this).parent('div.pure-control-group').remove();
            x--;
        })
        // form submit function
    $("#addTripForm").on("submit", function(e) {
        // stop form submission
        e.preventDefault();
        $.ajax({
            url: "post.php?type=Trip",
            type: "POST",
            data: $("#addTripForm").serialize(),
            success: function(data, textStatus, jqXHR) {
                $('.form-group').hide();
                $('.bg-success').show();
                $('#saveChanges').hide();
                //window.location.reload();
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('.bg-danger').show();
            }
        });
    })
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Pass html input array values to php script via ajax</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <style type="text/css">i,i:hover{color:#0078e7;cursor:pointer;}</style>


</head>

<body>
    <form class="pure-form pure-form-aligned form-horizontal" id="addTripForm">
        <fieldset>
            <div class="pure-control-group">
                <label for="deliveryAddress[]">Address</label>
                <input name="deliveryAddress[]" type="text" placeholder="Address...">
                <i class="fa fa-plus-circle"></i>
            </div>
            <div class="pure-controls">
                <button type="submit" class="pure-button pure-button-primary">Submit</button>                
            </div>
        </fieldset>
    </form>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="js.js"></script>
</body>

</html>

答案 1 :(得分:0)

您好尝试使用formData的对象

var deliveries = new Array();
        $('#addTripForm input[name="deliveryAddress"]').each(function (){
            deliveries.push($(this).val()); 
        });

var formData = new FormData()
formData.append("deliveryAddress",deliveries);

$.ajax({
        url : "/admin/PHPClasses/addToDB.php?type=Trip",
        type: "POST",
        data : formData,
        cache: false,
        contentType: false,
        processData: false
        success: function(data, textStatus, jqXHR)
        {
            $('.form-group').hide();
            $('.bg-success').show();
            $('#saveChanges').hide();
            window.location.reload();
         },
         error: function (jqXHR, textStatus, errorThrown)
         {
            $('.bg-danger').show();
         }
});