Ajax response not working 10% of the time
My problem is that works almost 90% of the time, but it doesn't work 10%. I just get nothing. Its using a drop down box with a onChange event.
<script type="text/javascript">
function showCourse(str)
{
if (str=="")
{
document.getElementByI开发者_C百科d("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getcourse.php?q="+str,true);
xmlhttp.send();
}
</script>
<div>
<label for="department">Department</label>
<select name="departments" onchange="showCourse(this.value)">
<option>Select a department:</option>
<?php
for ($i = 0; $i < sizeof($mySchool->departments); $i++) {
echo "<option value=\"" . $mySchool->departments[$i]->id . "\">" . $mySchool->departments[$i]->title . "</option>\n ";
}
?>
</select>
<span id="departInfo">Choose from the following.</span>
</div>
<div id="txtHint"></div>
Then finally here is what the ajax is calling in getcourse.php
<?php
require_once('auth.php');
$q = $_GET["q"];
$sql = "SELECT * FROM courses WHERE department_id = '" . $q . "'";
$result = mysql_query($sql);
echo "<table border='1' width='600'>
<tr>
<th>Link</th>
<th>Section</th>
<th>Name</th>
<th>Map ID: </th>
</tr>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['link'] . "</td>";
echo "<td>" . $row['section'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['map'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Newer versions (8+, I think) of MISE are caching the AJAX responses. Strange, but true. You can't fool MSIE by setting no-cache or similar headers, MSIE knows better which cases should be AJAX responses cached (guys at MS thinks: always) - so the best to do is use unique URLs, say:
xmlhttp.open("GET","getcourse.php?q=" + str + "&rnd=" + (+new Date()),true);
(Personal note: I have Firefox, Chrome, Opera, MSIE6(!) installed on my Linux, and I've tested my app with all of these browsers - you can imagine, it was such a surprise when the user said, it does not works on his machine, the initial screen appears but no further changes displayed. I have had to borrow a notebook with Windows from one of my friend.)
精彩评论