Jquery post:使用foreach循环处理$ _POST复选框?

时间:2014-07-20 18:11:56

标签: php jquery ajax post foreach

就其自身而言,当(controlpanel.php)输入html名称为"复选框[]",时,此php可用于删除多个值但是我不确定如何使用jquery 处理这些$ _POST值?我试过把"复选框[]"在身份证上,但没有成功。当我尝试vardump($ _ POST)时,无论勾选多少个复选框,我每次都得到相同的值。

test_process.js

$('#delete_submit').on('click', function(event) {
    alert("Test");
    event.preventDefault();
    var delete_value = $('#checkbox').val();
    $.post('ajax/name.php', {delete_template: delete_value}, function(data) {
        $('div#delete_data').text(data);
   });      
});

AJAX / name.php

<?php
include('C:\xampp\htdocs\email1\class\db.php');
require_once('C:\xampp\htdocs\email1\config\db.php');
require_once('C:\xampp\htdocs\email1\class\Login.php');

$login = new Login();
$user = $_SESSION['user_name'];
$db = new Database();
$db->connect();

    //delete
if (isset($_POST['delete_template'])) {
foreach($_POST as $value){
        $db->delete('templates','template_name="'.$value.'"');
        echo $value. " has been successfully deleted.";
}
}

Controlpanel.php

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>

<form action="ajax/name.php" name="delete_template_form" id="delete_template_form" method="post">
<?php print "<table border=\"1\">
<th>Template Name</th>
<th>Template Description</th>
<th> </th>";
foreach($res as $row){ 
echo "<tr>";
echo "<td>". $row['template_name']. "</td>";
echo "<td>". $row['template_description']. "</td>";
echo "<td><input type=\"checkbox\" value=".$row['template_name']." name=\"checkbox\" id=\"checkbox\"></td>";
echo "<tr/>"; 
} 
print "</table>"; ?>
<br/><button type="button" name="delete_submit" id="delete_submit">Delete</button>
</form>
<div id="delete_data"></div>

<script type="text/javascript" src="test_process.js"></script>
</body>
</html> 

1 个答案:

答案 0 :(得分:1)

id应该是唯一的,因为您对每个复选框使用相同的id - &gt; id=\"checkbox\"var delete_value = $('#checkbox').val();只会选择id=\"checkbox\"的第一个实例。

1-将您的复选框更改为数组(name=\"checkbox[]\"),将id更改为唯一(id=\"checkbox".$row['id'].") -

echo "<td><input type=\"checkbox\" value=".$row['template_name']." name=\"checkbox[]\" id=\"checkbox".$row['id']."\"></td>";

2-更改您的javascript以序列化表单输入并将其作为您的数据发送$('#delete_template_form').serialize() -

$.post('ajax/name.php', $('#delete_template_form').serialize() , function(data) {
      $('div#delete_data').text(data);
});    
然后在你的php中,循环选中你的复选框

if (isset($_POST['checkbox'])) {
foreach($_POST['checkbox'] as $value){
        $db->delete('templates','template_name="'.$value.'"');
        echo $value. " has been successfully deleted.";
}