我正在尝试创建一个下拉列表,它将更新页面上的文本而不刷新页面。更新的文本将由php函数提供,该函数从下拉列表中传递一个值。现在,我的下拉列表什么都没做,但这是我设法得到的地方:
webpage.php:
我的下拉菜单。由数据库填充。
<form method='post'>
<select name="skill1_level" id="skill1_level" onchange="skill1ValueChange(this.value)">
// PHP to dynamically populate list from the DB
<?php foreach ($skill_levels as $key => $skill_levels_list): ?>
<option value=""><?= $skill_levels_list->skill_level ?></option>
<?php endforeach ?>
</select>
</form>
我的div。目前只加载默认字符串。需要弄清楚在提交下拉列表时如何进行此更改。不知道如何在这里使用AJAX。
<div class="panel-body" id="skill1_text">
<?php echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, 1, $dbh); ?>
</div>
functions.js。提交下拉列表时要调用的Javascript。调用PHP函数。
function skill1ValueChange(skill_level) {
$.ajax({
url: 'functions.php',
type: 'POST',
data: {option : skill_level},
success: echoSkill($hero->skill1_desc, $placeholders, $id_hero, 1, skill_level, $dbh) {
console.log("Data sent for skill1.");
}
});
的functions.php。根据下拉值对我的数据做一些事情,然后回显结果字符串。
function echoSkill ($skill_desc, $placeholders, $id_hero, $skill_num, $skill_level, $dbh) {
$skill_values = fetchSkillValues($id_hero, $skill_num, $skill_level, $dbh);
$skill_values = array($skill_values[0]->skill_x, $skill_values[0]->skill_y, $skill_values[0]->skill_z, $skill_values[0]->skill_a);
$skill_desc = str_replace($placeholders, $skill_values, $skill_desc);
echo $skill_desc;
}
非常感谢您提供的任何帮助和解释!
答案 0 :(得分:1)
最简单的方法是从functions.php
返回HTML(实际上,您应该让它引用包含functions.php
页面的其他页面并回显{{1功能)文件:
页面:
echoSkill()
<强>的functions.php 强>
<!-- I assume you already have the libraries...-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<form method='post'>
<!--You can just add the change in the jQuery instead of inline js -->
<select name="skill1_level" id="skill1_level">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
<!-- This is where your empty div will fill with the php content -->
<div class="panel-body" id="skill1_text"></div>
</form>
<script>
// Select by the <select> named "skill1_level"
// When changed...
$("select[name='skill1_level']").change(function() {
// Assign the selection's value
var OptionVal = $(this).val();
$.ajax({
url: 'functions.php',
type: 'post',
data: { option: OptionVal },
// You need a success function here
success: function(response) {
// This will print out the response from your php page
// to the div on this page called "skill1_text"
$("#skill1_text").html(response);
}
});
});
</script>