【发布时间】:2017-12-28 08:47:08
【问题描述】:
我有一个由两个按钮组成的按钮组,每个按钮都分配了一个 id 和一个值:
echo "<div style='margin-top:20px;' class='btn-group'>
<button type='button' class='btn btn-primary' id='btnconventional' value='conventional' style=' border-radius: 3px;'>Conventional Units</button>
<button type='button' class='btn btn-primary' id='btnsi' value='si' style=' border-radius: 3px;'>SI Units</button>
</div>";
然后我想根据将通过此 ajax 脚本发送的按钮的值提交查询和表格结果:
<script>
$("#btnconventional").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
Metric: $('#btnconventional').val(), // < note use of 'this' here
},
success: function(result) {
alert('Viewing conventional units');
},
error: function(result) {
alert('error');
}
});
});
</script>
现在,当我尝试获取变量并运行我的代码时,除了 else 语句之外什么都没有出现:
if(isset($_POST['Metric']) && !empty($_POST['Metric'])){
$sql2 = "Select DISTINCT Record_id,Test_Group,Test_Name,Result,subtests.Units from tests,medicalrecords,subtests WHERE medicalrecords.CommonID=".$comid." and medicalrecords.Subtest_id IS NOT NULL AND medicalrecords.Subtest_id=subtests.Subtest_id AND subtests.Test_id=tests.Test_id and tests.Test_Group='CBC'";
$result2 = $conn->query($sql2);
echo $_POST['Metric'];
echo "<table style='margin-top:10px;' class='table table-hover table-striped table-bordered table-condensed' width='100%' cellspacing='0'>
<thead>
<tr bgcolor='#d3d3d3'>
<th style='text-align:center;'>CBC</th>
<th style='text-align:center;'>Result</th>
</tr>
</thead>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<tr>
<td style='text-align:center;'>".$row2['Test_Name']."</td>
<td style='text-align:center;'>".$row2['Result']." ".$row2['Units']."</td>
</tr>";
}
echo "<tfoot>
<td></td>
<td></td>
</tfoot>
</table>";
echo "<button onclick='hideLabResult();'>Back</button>";
}
else echo "Nope";
单击按钮后显示成功警报,但单击后仍显示“否”,它没有进入 if 语句,我似乎找不到方法,我是 ajax 的初学者,我非常感谢任何提示或帮助。
【问题讨论】:
-
尝试将 Metric 放在引号内,例如
"Metric": $('#btnconventional').val(), -
不幸的是,这不起作用,但我确信它不带引号也有效,因为我已经在不同的页面上尝试过类似的请求,但我已经在页面顶部提取了结果请求方法发布并在其中运行查询并运行,但现在我不想只在该范围内完成它
-
$comid设置在哪里?你也对 SQL 注入持开放态度。 -
@Lalati 你把你的脚本标签放在哪里了?
-
@LawrenceCherone 在这个阶段我并不关心 SQL 注入,我知道我必须使用准备好的语句,并且 $comid 在我的页面开头通过 url 检索,因为它是发送的从另一个页面获取,我认为它与问题无关,我尝试明确指定它但仍然是同样的问题