选择下拉项时,JavaScript函数不会更新网页上的列表

时间:2014-01-19 20:11:47

标签: javascript php html

我有一个网站,我希望在选择列表1中的项目时使用javascript函数更新列表2和列表3.

enter image description here

HTML

<select name="department_list" selected="All" style="min-width:80px" onchange="checkTeacherList(this.value, '<?php echo $user_login;?>');" >
... code to populate List 1
</select>
</td>

<td>
<div id="departmentTeachers"></div>
</td>

<td>
<div id="nondepartmentTeachers"></div>
</td>

JAVASCRIPT

<script type="text/javascript">
function checkTeacherList(departmentName, schoolName) 
{
var xmlhttp;

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
{
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
 document.getElementById("departmentTeachers").innerHTML = data["teacher1"];
 document.getElementById("nondepartmentTeachers").innerHTML = data["teacher2"];
 }
}

var d = new Date();

xmlhttp.open("GET","http://website/getTeacherInfo.php?schoolName="+schoolName+"&departmentName="+departmentName+"&nocache="+d.getSeconds(),true);

alert ("test1"); // this alert displays
var data = JSON.parse(xmlhttp.responseText);
alert ("test2"); // this alert does not display

xmlhttp.send();
}
</script>

PHP

..... code that produces two strings $teacherList1 & $teacherList2 (which work correctly

// return with a JSON type
header('Content-Type: application/json');
// reply with json format
echo json_encode(array('teacher1' => $teacherList1, 'teacher2' => $teacherList2));

1 个答案:

答案 0 :(得分:0)

在IE中,列表内容不能简单地用innerHTML替换。

如果服务器响应中有一个存储如下的数组:

var options=['A','B','C','D'];

你可以这样做:

var deptteachers=document.getElementById('departmentTeachers');
deptteachers.innerHTML=''; //clear the list

for (var i=0;i<options.length;i++){
  var option=document.createElement('option');
  options.innerHTML=options[i];
  option.setAttribute('value',options[i]);
  deptteachers.appendChild(option); //add the element; this works in IE
}

编辑:

function load_select(id,objs){
  var d=document.getElementById(id);
  d.innerHTML='';

  for (var i=0;i<objs.length;i++){
        var option=document.createElement('option');
    option.innerHTML=objs[i];
    option.setAttribute('value',objs[i]);
    d.appendChild(option);
  }  //for
}

然后调用函数:

load_select('teacherList1',data);

如果要优化代码,可以在一个函数中进行数据拆分。确保“data”是一个字符串数组。