在这种情况下,我需要对通过发送到php脚本的ajax请求选中的每个复选框进行插入查询,该脚本将在mysql中进行插入。
我知道如何在没有ajax调用的情况下通过简单的表单提交来实现这一点,表单提交将groups[]这样的变量作为数组,并在php中为数组中的每个值运行foreach循环。
如何通过post-ajax请求向数组发送请求?
示例代码:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
请帮忙,我知道这可能很容易,但我只是不明白。伙计们,请不要给出任何jquery或类似的例子,因为我想要纯html、javascript和php解决方案。
感谢社区。。。
这是Javascript函数:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
和php脚本:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
编辑
把这两行改一下。
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
您可以使用两种方法来实现这一点,
-
您可以使用post-type ajax调用
-
您可以使用JavaScript获取所有选中的复选框值,使逗号分隔字符串,并将其传递到一个变量中
这就是你所能做的……:)