【问题标题】:Pass Multiple Checkboxes to PHP via Ajax通过 Ajax 将多个复选框传递给 PHP
【发布时间】:2013-09-06 03:05:39
【问题描述】:

用户可以从复选框中进行选择。我想通过 jquery 将复选框作为数组获取,然后通过 ajax 传递给 php。似乎我无法获得数组和进程。我在 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";
}

【问题讨论】:

  • 检查了 js 以查看是否填充了 buckets?检查 php 以查看是否填充了 POST - 一点调试就大有帮助

标签: php jquery ajax checkbox


【解决方案1】:

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

所以data: buckets, 应该是data: {buckets : buckets},那么你可以使用$_POST['buckets']

如果你只是使用 data: buckets,,那么$_POST已经是你想要的数据了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多