通过Ajax将多个复选框传递给PHP

时间:2013-09-03 01:32:57

标签: php jquery ajax checkbox

用户可以选择复选框。我希望通过jquery将复选框作为数组,然后传递给php通过ajax。我似乎无法获得数组和进程。我已经在SO上看到了其他答案,但似乎都没有。

HTML / PHP

<?php foreach ( $results['buckets'] as $bucket ) { ?>
    <div><?php echo $bucket->name ?></div>
    <input type="checkbox" name="buckets[]" id="<?php echo strtolower( $bucket->name ) ?>" class="buckets" value="<?php echo $bucket->id ?>" style="visibility: hidden" /><label for="<?php echo strtolower( $bucket->name ) ?>" class="<?php echo strtolower( $bucket->name ) ?>"><?php echo $bucket->name ?></label>
<?php } ?>

JS

$( function() {

    $( "#form" ).submit( function() {

        var buckets = new Array();
        $( "input[name='buckets[]']:checked" ).each( function() {
                buckets.push( $( this ).val() );
        } );
        var valid = false;

        $.ajax( {

            type: "POST",
            url: "/scripts/validateBucketSelect.php",
            data: buckets,
            cache: false,
            async: false,

            success: function( error ) {

                if ( error == "null" ){

                    valid = true;

                } else {

                    $( ".errorMessage" ).html( error );
                }
            }
        } );

        return valid;
    } );
} );

PHP

$postData = $_POST;

if ( count( $postData['buckets'] ) < 3 ) {
    echo "Oops! You have to select at least 3 buckets.";
} elseif ( count( $postData['buckets'] ) > 5 ) {
    echo "Oops! You cannot select more than 5 buckets.";
} else {
    echo "null";
}

1 个答案:

答案 0 :(得分:2)

buckets是一个数组,但您需要php脚本中的key

因此data: buckets,应为data: {buckets : buckets},然后您可以使用$_POST['buckets']

如果你只是使用 data: buckets,,然后$_POST已经是您想要的数据。