将元素ID传递到数组中以进行POST表单处理


Pass element IDs into an array for POST form process

假设我已经用php循环创建了一系列图像->

<img src="http://..._1.jpg" class="profile-thumb" id="12345678">
<img src="http://..._2.jpg" class="profile-thumb" id="12345677">
<img src="http://..._3.jpg" class="profile-thumb" id="12345676">

用户可以通过点击jquery style a la->来选择图像元素

    $(".profile-thumb").click(function () {
        if ($(this).hasClass("active")) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    });

这样,当你点击一个图像时,它会在图像元素中添加一个".active"类->

<img src="http://..._3.jpg" class="profile-thumb active" id="12345676">

如何将所有选定的元素ID传递到一个数组中,以便在使用PHP的表单过程中使用?

用户旅程:

单击照片->将ID添加到阵列->单击提交按钮->使用POST阵列使用所有ID执行功能(例如,使用标识为活动的ID向所有用户发送电子邮件)


我想通过AJAX调用将数组传递给一个循环,并将输出回声到#post-infodiv->

    $.get('post.php', function(data) {
        $('#post-info').html(data);
    });

然后,我将如何读取带有foreach循环的POST数组?


解决方案:

HTML:

<button id="share" class="off">
    <span>Sharer</span>
</button>
<div id="sharer">
<!-- Array will echo here -->
</div>

Javascript:

    $("#share").click(function () {
        //Create var array
        var list = $('.active-profile').map(function(){return this.id;}).toArray();
        $.post('sharer.php', {ids:list}, function(data) {
            $('#sharer').html(data);
        });
    });

PHP(sharer.PHP)

        foreach ($_POST['ids'] as $id) {
            echo 'ID: ';
            echo $id;
        }

javascript数组(列表)通过jquery POST发送,并在#sharerdiv 中回显

$('.profile-thumb.active').map(function(){return this.id}).toArray();

此外,您可以简单地使用:而不是if-hasClass-removeClass-else-addClass

$(".profile-thumb").click(function () {
    $(this).toggleClass("active");
});

演示:http://jsfiddle.net/ErVbS/

要向php发送一个值数组,需要使用稍微不同的语法。对于每个id,你可以创建一个类似的url。

http://test.com/?img_id[]=1&img_id[]=2&img_id[]=3

这将使您可以在php中获得值img_id作为数组。

$_POST['img_id'] // array of values. 
foreach ($_POST['img_id'] as $id) {
  print $id;
}  
// 1
// 2
// 3