我正在进行一个使用jQuery/ajax从选定复选框中检索名称和值的项目。我在主页上使用php设置了复选框的名称和值,现在我希望在单独的php脚本中使用$_POST提取名称,这样我就可以使用这些名称从MySQL中删除项目。
$("#deleteproject").click(function () {
var names = [];
$('#projectcheckbox input:checked').each(function() {
//all checkbox names are put in array
names.push({name: $(this).attr('name'), value: $(this).val()});
});
alert($.param(names));
return false;
});
上面的alert($.param)以val1.name和val1.value格式返回选中的复选框。
//run delete_project.php to erase projects from database
$.ajax({
type: "post",
url:"delete_project.php",
data: names,
cache: false,
success:function() {
alert(names + ' deleted')
}
});
在过去的几天里,我一直在寻找答案,我希望有人能帮我解决这个问题。
I would prefer using html part in this way first, cos it's more flexible and easy in your case;
<input type="checkbox" name="projectcheckbox[]" value="foo_project" />
<input type="checkbox" name="projectcheckbox[]" value="bar_project" />
...
Or printing out the db results at first;
foreach ($projects as $project) {
print '<input type="checkbox" name="projectcheckbox[]" value="'.$project.'" />';
}
Then calling jQuery.serialize
will give you a data stuff like;
projectcheckbox[]=foo_project&projectcheckbox[]=bar_project ...
PHP part (after post);
foreach ((array) $_POST['projectcheckbox'] as $pro) {
// do something with $pro = foo_project or bar_project etc...
// THIS PART FOR SECURITY GUYS :)
// BUT! DO NOT FORGET TO SECURE YOUR DATA ($pro) HERE!!!!!
}