1

请帮我处理我的代码,这是我的代码片段。我正在使用 ajax 来获取我选择的单选按钮的数据,我希望保留我选择的复选框。请帮助我如何..

函数.php

<?php
$sql = "SELECT * FROM tbl_func";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
$let = $row['letter'];
?>
<form action="func.php" method="post">
<input onchange="let()" name="letter" type="radio" value="A" <?php if($let == "A") echo "checked";?>/>A
<input onchange="let()" name="letter" type="radio" value="B" <?php if($let == "B") echo "checked";?>/>B
<script>
function let(){
    $.ajax({
        type:"post",
        url:"ajax.php",
        data:{
            letter_val:$("[name=letter]:checked").val(),
            },
        success:function(msg){
            document.getElementById("div").innerHTML = msg;
            }
    })
    }
</script>
<br /><br />
<div id="div"></div>
<br />
<?php if(isset($let)) {?>
    <input type="submit" name="update" value="update" />
<?php }else{?>
    <input type="submit" name="submit" value="submit" />
<?php }?>
</form>
<?php
if(isset($_POST['submit'])){
    $letter = $_POST['letter'];
    $val = $_POST['val'];
    $val_sel = "";
    $val_temp = "";
    foreach($val as $val_temp){
        $val_sel .= $val_temp.",";
    }
    $val_trim = rtrim($val_sel,",");
    $sql = "INSERT INTO tbl_func (letter,val) VALUES('$letter','$val_trim')";
    $res = mysql_query($sql) or die (mysql_error());
    if($res) echo "success";
    }
?>

ajax.php

<?php
$letter_val  = $_POST['letter_val'];
$sql = "SELECT * FROM tbl_func";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($res);
$val = $row['val'];
$val_arr = explode(",",$val);
$val_temp = "";

if($letter_val == "A"){
?>  
<input type="checkbox" value="1" name="val[]" 
<?php 
foreach($val_arr as $val_temp){
    if($val_temp == 1) echo "checked";
} 
?>/>1
<input type="checkbox" value="2" name="val[]"
<?php 
foreach($val_arr as $val_temp){
    if($val_temp == 2) echo "checked";
} 
?>
/>2
<?php   
}
if($letter_val == "B"){
?>  
<input type="checkbox" value="3" name="val[]" 
<?php 
foreach($val_arr as $val_temp){
    if($val_temp == 3) echo "checked";
} 
?>
/>3
<input type="checkbox" value="4" name="val[]"
<?php 
foreach($val_arr as $val_temp){
    if($val_temp == 4) echo "checked";
} 
?>
/>4
<?php   
}
?>

我正在使用此代码,但没有运气。谢谢你们

4

1 回答 1

0

执行以下操作,您将了解问题的原因:

print_r($val_arr);

foreach($val_arr as $val_temp){
    if($val_temp == 2) echo "checked";
    echo $val_temp;
}
于 2013-09-26T07:21:50.223 回答