使用jQuery ajax将Javascript数组转换为php

问题描述:

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

Possible Duplicate:
Passing JavaScript Array To PHP Through JQuery $.ajax

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

I'm trying to pass some variables gathered from n dynamically generated inputs to php with ajax.

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

这是动态生成的输入(可能为1或100). 现在,如果我不使用ajax提交它们,只需执行以下操作即可在php中提供一个数组

This is the dynamically generated input(there could be 1 or 100). Now, if I submit them without ajax it gives me an array in php by simply doing

$services = $_POST['service'];

但是如果我想用ajax而不刷新页面怎么办?

But what if I want to do it with ajax without refreshing the page?

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>");

        }
    }
});

它仅发送第一个服务变量,而不发送带有其他(如果有)变量的完整数组.有什么建议吗?

It only sends the first service variable and not a complete array with the others(if there are) variables. Any suggestions?

您遇到的问题是选择器('#services')仅采用第一个输入值.您应该删除id并按如下所示序列化表单.

you problem that selector ('#services') takes only first input value. You should remove id and just serialize form as below.

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

If all you need to pass is all values from form you can use

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

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

And then in $_POST['service'] will be an array of inputs values.

例如:

<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中获得一个数组:

And then in save.php you can get an array in $_POST:

var_dump($_POST['service']);

希望这正是您所需要的.

Hope that's is exactly what you need.