Javascript 如何在单击复选框时从数据库检索值?

Javascript 如何在单击复选框时从数据库检索值?,javascript,php,jquery,mysql,Javascript,Php,Jquery,Mysql,嗨,我有三个复选框,我想知道我选择了哪一个复选框,关于那个复选框值应该从数据库中检索 这是我的复选框 <input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label> <input type="checkbox" name="test" value="Ecg" style="margin-top:

嗨,我有三个复选框,我想知道我选择了哪一个复选框,关于那个复选框值应该从数据库中检索

这是我的复选框

<input type="checkbox" name="test" value="X-Ray" style="margin-top:10px;margin-left:120px;"><label>X-Ray</label>
<input type="checkbox" name="test" value="Ecg" style="margin-top:10px;margin-left:20px;"><label>ECG</label>
<input type="checkbox" name="test" value="Blood Test" style="margin-top:10px;margin-left:20px;"><label>Blood Test</label>

如何获得所需的输出?任何帮助都将不胜感激

您可以使用jquery选择器
:checked
按住特定的
输入
复选框。因此,javascript中的类似内容应该可以帮助您开始:

 $( "input" ).on( "click", function() {
   var sel = $( "input:checked" ).val(); 
       //Here you can just make a simple ajax request to a php script passing the 
       //specific checkbox value and let that script perform the mysql query.
       $.post( "test.php", { test: sel })
        .done(function( data ) {
         alert( "Completed");
        });
});
您的
test.php
脚本可能如下所示:

<?php
   $test = $_POST["test"]; 

   //Replace with your sql database credentials
   $con=mysqli_connect("example.com","peter","abc123","my_db"); 

  // Check connection
 if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $result = mysqli_query($con,"SELECT SUM(price) from test where test='".$test."'");
 mysqli_close($con);
?>

我认为最好的解决方案是将所有价格作为JavaScript变量输出到页面的某个地方,让我们稍微修改一下HTML

<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>

确保
prices
变量的键与

值相匹配,为什么我看不到服务器端脚本?@OP:你是否愿意检查别人给出的答案???这不是给你的吗?如果有人解释为什么答案被否决,我会很感激的?
<input type="checkbox" class="chkbox-update" name="test" value="X-Ray"><label>X-Ray</label>
<input type="checkbox" class="chkbox-update" name="test" value="Ecg"><label>ECG</label>
<input type="checkbox" class="chkbox-update" name="test" value="Blood Test"><label>Blood Test</label>
<script>
var prices = {"X-ray": 3900, "ECG": 2000, "Blood Test": 1200};
</script>
$('.chkbox-update').click(function() {
    var total;
    $.each($('.chkbox-update'), function(k,v) {
        total += prices[$(this).val()];
    });
    $('#result').text('The total price is '+total);
});