我有3个PHP变量值,我想根据从下拉菜单中选择的HTML选项显示,而不刷新页面。
<p>
<label for="package" class="formlbl">I want to Enroll In:</label>
<select name="package" id="package">
<option selected="selected" value=""></option>
<option value="full_package">Complete Package</option>
<option value="training">Only Training</option>
<option value="counselling">Only Counselling</option>
</select>
</p>
&#13;
我想要的是当他选择完整包时它应该回显变量1,当他选择训练它应该回显变量2等等而不刷新页面。
请告诉我应该怎么做。值和变量在代码中有效。
答案 0 :(得分:1)
由于PHP只是一种服务器端语言,一旦将响应发送到客户端,php就无法再刷新页面上的任何内容。
您需要使用javascript才能在不重新加载新页面(也称为动态内容)的情况下更改内容。您可以使用名为jquery的框架轻松完成此操作。
使用此html行将jquery添加到您的网页:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
然后使用此html模板进行下拉列表:
<!-- make each item in your dropdown an <a> with an ID -->
<ul class="dropdown">
<li onclick="toggleResponse('comp')">Complete </li>
<li onclick="toggleResponse('pack')">Package Only </li>
<li onclick="toggleResponse('train')">Training Only </li>
<li onclick="toggleResponse('couns')">Counselling </li>
<ul>
<!-- give every response the same class, and individual IDs -->
<span class="response" id="comp"><?php echo var1 ?></span>
<span class="response" id="pack"><?php echo var2 ?></span>
<span class="response" id="train"><?php echo var3 ?></span>
<span class="response" id="couns"><?php echo var4 ?></span>
<style>
// let all the responses be hidden initially
.response {
display: none;
}
</style>
<script type="text/javascript">
function toggleResponse (id) {
// hide any responses that might be showing
$('.response').hide();
// show the response for this option
$('#' + id).show();
}
</script>
答案 1 :(得分:0)
这可能是最快捷,最简单的方法。
小提琴示例:https://jsfiddle.net/te36zy18/
HTML
<p>
<label for="package" class="formlbl">I want to Enroll In:</label>
<select name="package" id="package">
<option selected="selected" value=""></option>
<option value="full_package">Complete Package</option>
<option value="training">Only Training</option>
<option value="counselling">Only Counselling</option>
</select>
</p>
<div id="full_package" class="package"><?php echo full_package;?></div>
<div id="training" class="package"><?php echo training;?></div>
<div id="counselling" class="package"><?php echo counselling;?></div>
的jQuery
$("#package").on("change", function(){
var package = $(this).val();
$(".package").hide()
$("#" + package).show();
});
CSS
.package {display: none'}