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

标签 php javascript jquery

假设我已经使用 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 样式来选择图像元素 ->

    $(".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-info div ->

    $.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 发送并在 #sharer div 中回显

最佳答案

$('.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 传递到数组中以进行 POST 表单处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843383/

相关文章:

Phpunit:在功能测试中的类中添加方法

PHP/MySQL : How to create a comment section in your website

javascript - HowlerJS 步骤函数不会更新搜索时的范围输入值

javascript - Jquery 从 span 中删除文本

javascript - 使用 Bootstrap 的网格系统设计轮廓框

php - jQuery 将所选值的名称发送为空? Ajax

php - 使用 PHP MYSQL 向表中插入一行

javascript - 以 Angular 观察 Controller 之间的变化

javascript - Appcelerator - Javascript - 丢失引用

jquery - 正则表达式不忽略字母大小写