这个Ajax没有按原样从它的'PHP文件中检索任何信息,当在Firebug中检查Javascript时,我发现responseText返回未定义。
这是Javascript:
function getTeams(sport)
{
var req = new XMLHttpRequest();
var nextTeam, nextOption;
// callback function, using "closure"
req.onreadystatechange = function()
{
if( (req.readyState == 4) && (req.status == 200) )
{
var result = req.responseText;
// array teams created here
var teams = result.split(", ");
for(var i = 0; i < teams.length; i++)
{
nextTeam = teams[i];
nextOption = new Option(nextTeam);
/* add the new option to the option list
("null" for IE5, "-1" for all other browsers) */
try
{
document.getElementById("teamsList").add(nextOption, -1);
}
catch(e)
{
document.getElementById("teamsList").add(nextOption, null);
}
}
}
} // end of closure
req.open("GET", "favoriteSport.php?sport=" + sport, true);
req.send(null);
}<br /><br />
这是PHP:
<?php
$sport = $_GET["sport"];
$teams = array("basketball" => "Atlanta Hawks, Chicago Bulls, New York Knicks",
"baseball" => "Atlanta Braves, Chicago Cubs, New York Yankees",
"football" => "Atlanta Falcons, Chicago Bears, New York Giants");
return $teams[$sport];
?><br /><br />
...这里是相关的html:
<select onchange = "getTeams(this.value);">
<option>
--select a sport--
</option>
<option value = "basketball">
basketball
</option>
<option value = "baseball">
baseball
</option>
<option value = "football">
football
</option>
</select>
<select id = "teamsList"></select>
答案 0 :(得分:1)
看起来你的问题就在这里:
return $teams[$sport];
尝试
echo $teams[$sport];