使用jquery将多个选择表单作为数组发送

时间:2012-10-05 16:27:18

标签: jquery ajax arrays select

目前,我正在从多个选择框中发布单个值。如果我想将变量作为数组发布到字段活动和yearOfBirth而不是字符串,我如何通过更改当前代码来实现此目的?

谢谢!

function showUser() {
    // getting the value that user typed
    var firstName = $("#firstName").val();
    var lastName = $("#lastName").val();
    var sex = $("#sex").val();
    var registrationType = $("#registrationType").val();
    var activity = $("#activity").val();
    var yearOfBirth = $("#yearOfBirth").val();

    // forming the queryString
    var data = 'search_firstName=' + firstName + '&search_lastName=' + lastName + '&search_registrationType=' + registrationType + '&search_activity=' + activity + '&search_yearOfBirth=' + yearOfBirth + '&search_sex=' + sex;

    // if searchString is not empty
    if (firstName || lastName || sex || registrationType || activity || yearOfBirth) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "groupQsearchMember.php",
            data: data,
            beforeSend: function() {
                $('#whileLoading').show();
                $('#results').hide();
            },
            complete: function() {
                $('#whileLoading').hide();
            },
            success: function(html) {
                $("#results").html(html);
                $("#results").fadeIn(700);
            },

        });
    }
    return false;
};​

2 个答案:

答案 0 :(得分:0)

您需要将选择字段的值拆分为数组,只需添加.split(','),然后遍历数组以添加数组括号,例如:

var registrationTypeString = "";
$("#registrationType").val().split(',').each(function(item){
    registrationTypeString += '&registrationType[]=' + item;
});

//..

var data = 'search_firstName=' + firstName + '&search_lastName=' + lastName + registrationTypeString + '&search_activity=' + activity + '&search_yearOfBirth=' + yearOfBirth + '&search_sex=' + sex;

使用选择字段执行此操作,然后您将在PHP中使用数组。

答案 1 :(得分:0)

不要手动构建POST数据,而是确保表单元素具有所需的name属性并创建data,如下所示:

 var data = $("#firstName, #lastName, #sex, #registrationType, #activity, #yearOfBirth").serialize();

根据jQuery docs for serialize(),将使用标准网址编码表示法创建“文本字符串。”