我正在使用以下脚本动态添加到 html。
<script type="text/javascript">
$(document).ready(function ()
{
$('<div/>',
{
'class' : 'extraPerson', html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function ()
{
$('<div/>',
{
'class' : 'extraPerson', html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml()
{
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=family_member_name]')[0].name="family_member_name" + len;
$html.find('[name=gender]')[0].name="gender" + len;
$html.find('[name=age]')[0].name="age" + len;
$html.find('[name=fdegrees]')[0].name="fdegrees" + len;
$html.find('[name=fcourse]')[0].name="fcourse" + len;
$html.find('[name=blood_group]')[0].name="blood_group" + len;
$html.find('[name=cell_no]')[0].name="cell_no" + len;
return $html.html();
}
</script>
现在我在有onChange
事件时<select>
调用AJAX 方法id="fdegrees"
。我收到正确的 AJAX 响应,但无法添加到 HTML。它的代码如下。
<div class="extraPersonTemplate">
<div class="controls controls-row">
<select name="fdegrees" id="fdegrees" onChange="getDegree1('familyfinddegree.php?fdegrees='+this.value)">
<option value="">Select Degree</option>
<option value="1">Bachlor</option>
<option value="2">Master</option>
</select>
<div style="float:left" id="courses1">
<select name="fcourse">
<option>Select Courses</option>
</select>
</div>
</div>
</div>
用于 AJAX 功能的 Javascript。
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getDegree1(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('courses1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
// alert(strURL);
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
PHP文件给出的AJAX响应如下:
<?php
$degrees=$_REQUEST['fdegrees'];
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('gujarati_mandal');
$query="select course from courses where degree_id=$degrees";
$result=mysql_query($query);
$i=0;
?>
<select name="fcourse<?php echo $i?>">
<option>Select Course</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['course']?>"><?php echo $row['course']?></option>
<?php } ?>
</select>