Javascript array to php with jQuery ajax


Javascript array to php with jQuery ajax

可能的重复项:
通过 JQuery 将 JavaScript 数组传递给 PHP $.ajax

我正在尝试使用 ajax 将从 n 个动态生成的输入收集的一些变量传递给 php。

<input type="text" class="big" id="service" name="service[]" maxlenght="100"/>

这是动态生成的输入(可能有 1 或 100(。现在,如果我在没有 ajax 的情况下提交它们,它只需通过简单地

$services = $_POST['service'];

但是,如果我想在不刷新页面的情况下使用 ajax 执行此操作怎么办?

var action = $("form_act").attr('action');
var form_data = {
    service: $("#service").val(),
    ajax_request: 1
};
$.ajax({
    type: "POST",
    url: action,
    data: form_data,
    dataType: "json",
    success: function (response) {
        if (response.error == 'none')
            $("#form_content").slideToggle('slow', function () {
                $('#form_content').load('includes/db_setup_form.php');
                $("#form_content").delay(500).slideToggle('slow');
            });
        else {
            $("#ajax_response").html("<p>" + response.msg + "</p>");
        }
    }
});

它只发送第一个服务变量,而不是包含其他(如果有(变量的完整数组。 有什么建议吗?

您遇到选择器('#services'(仅接受第一个输入值的问题。您应该删除id并仅序列化表单,如下所示。

如果您只需要传递表单中的所有值,则可以使用

data: $('form#my-form').serialize() // this code puts all of the inputs into passable and readable for PHP, way.

然后在 $_POST['service'] 中将是一个输入值数组。

例如:

<form action="save.php" method="post" id="services">
    <input type="text" name="service[0]" value="1st Service" />
    <input type="text" name="service[1]" value="2nd Service" />
    <input type="text" name="service[2]" value="3rd Service" />
    <input type="text" name="service[..]" value=".. Service" />
    <input type="text" name="service[N]" value="N Service" />
</form>

在您的 JS 中:

$.post($('form#services').attr('action'), $('form#services').serialize(), function(response) {});

然后在 save 中.php您可以获得 $_POST 的数组:

var_dump($_POST['service']);

希望这正是您所需要的。

您应该按name属性选择输入,因为在 HTML 文档中有多个具有相同 ID 的元素是无效的。你的jQuery选择器知道它正在寻找应该是一个独特的元素,所以它在找到第一个元素后停止。此外,.val()函数仅查找所选元素集中第一个元素的值。

以下是我要更改的内容:

var form_data = {
    service: $("#service").val(),
    ajax_request: 1
   };

自:

var form_data = {
    service: $('[name="service[]"]').serialize(),
    ajax_request: 1
   };

这是一个演示:http://jsfiddle.net/sS7YP/

以下是.serialize()的文档: http://api.jquery.com/serialize

一种解决方案,它使用 jQuery.map() 创建service[]输入值的干净数组。

var $form = $('#form_id'),
    $inputs = $form.find('input[name^=service]'); // Do not select by ID
$form.on('submit', function(event) {
    // Build an array only containing the services values
    var values = [];
    $.map($inputs, function(e) {
        values.push(e.value);
    });
    event.preventDefault();
});

http://jsfiddle.net/eTU2y/1/