2

在搜索互联网后,我无法找到关于为什么我的 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);
        }
    }
}
4

0 回答 0