开发者

Cannot Seem To Get This AJAX Code To Run

I am trying to learn how to use ajax and i cant seem to figure out why the below code does not work. All it does is first create a valid XMLHttpRequest object when the page firsts loads and then inserts some text into a section of the pages div area.

Demo.js

var ajaxRequest;  // The variable that makes Ajax possible!
function newRequest()
{
    try
    {
        ajaxRequest = new XMLHttpRequest();
    ..
    }    
}

I call this by using the following:

Index.html

<script src="Demo.js" type="text/开发者_C百科javascript"></script>
</head>
<body onload="newRequest()">
    <div class="page_Disp">
    </div>

I then try to load some text from a file into the page using the following JS Function:

Demo.js

function openPage()
{
    ajaxRequest.onreadystatechange=function()
    {
        if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById("page_Disp").innerHTML=ajaxRequest.responseText;
            ajaxRequest.open("GET","ajax_info.txt",true);
            ajaxRequest.send();
        }
    }
}

The above is called using the following html code:

<a onclick="openPage()">Load TXT</a>

Can anyone see the problem that causes the script to not load and insert the data from the .txt into the section?


You are using a class on the element:

<div class="page_Disp">

But are trying to get it by id:

document.getElementById("page_Disp")

So you need to change it to an id to get it populated:

<div id="page_Disp">


I would expect your Demo.js to look like this

function openPage()
{
    ajaxRequest.onreadystatechange=function()
    {
        if (ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById("page_Disp").innerHTML=ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("GET","ajax_info.txt",true);
    ajaxRequest.send();
}

Otherwise the ajaxRequest will never get to send the request, because it was inside the code that responded to the request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜