对不起,我是新来的,我不太懂PHP。我想问我如何能生成动态文本框和标签依赖于一个弹出式菜单上的选择。我想使一个网站的wordpress,将有一个弹出菜单,显示论文的标题。我有一个名为wp_courses数组的数据库,其中有course_id, Thesis_ID, course_title,以及另一个名为Thesis的数组,其中有Thesis_ID,Thesis_Title。我希望当选择论文时,生成带有论文所具有的特定课程的文本框和带有课程标题的标签,以填充。我很困惑,我怎么能在函数中传递我的数据库。我可以用javascript做吗?
//所有的PHP代码
function showTextboxes(choise){
for(i=0;i<=choise;i++)
{
my_div.innerHTML = my_div.innerHTML +"<br>
<input type='text' name='mytext'+ i>";
}
$conn = mysqli_connect("localhost","root","","wordpress");
mysqli_query($conn,'SET NAMES utf8');
<label class='formLabel'>Title of thesis*</label><br />";
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);
echo"<select name='ThesisTitle' id='link_block' onChange='showTextboxes(this.selectedIndex);' required=''>
<option disabled='disabled' selected='selected' value=''></option>";
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}> {$row[Thesis_Title]}</option>";
}
echo"</select><br />";
<div id="my_div"></div>
将数据与前端代码分开通常是一个非常好的主意。
例如返回JSON字符串
PHP有一个内置函数json_encode来处理mysql的结果:https://stackoverflow.com/a/383664/5335350
JSON/对象的例子:
var Thesis = [{
Thesis_ID: 0,
Thesis_Title: 'My thesis title1'
}, {
Thesis_ID: 1,
Thesis_Title: 'My thesis title2'
}, {
Thesis_ID: 2,
Thesis_Title: 'My thesis title3'
}]
有了这些数据,现在用一点JS就可以完成你想要的了。HTML
HTML:<div id="courses">
<table>
<tr></tr>
</table>
<hr/>
<label for="course">Select course: <span></span>
<input name="course">
</label>
<select class="form-control" name="userName">
<option></option>
</select>
</div>
JS:
mag.module('courses', {
view: function(state) {
state.option = Thesis.map(function(thesis) {
return {
_selected: thesis.Thesis_ID == state.index ? true : null,
_text: thesis.Thesis_Title,
_value: thesis.Thesis_ID
}
});
state.select = {
_onchange: function(e) {
var i = e.target.selectedIndex
state.span = Thesis[i].Thesis_Title + ' ID:' + Thesis[i].Thesis_ID
}
}
}
});
下面是完整的工作示例: http://jsbin.com/qafupozemu/1/edit?html,js,output
希望有帮助!