在搜索互联网后,我无法找到答案为什么我的AJAX代码不起作用。我的任务是检索文本文件并使用AJAX将其显示到浏览器,但就绪状态在1处停止。示例文件是canada.txt,位于目录http://157.201.194.254/~ercanbracks
中。 .html和.js文件如下:
HTML文件:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js文件:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}