开发者

Can't get simple ajax example to work

I'm trying to learn some ajax. And I'm trying to get ajax to read a text file asynchronously.

heres my code:

<html>
<head> 
  <script type="text/javascript"> 
    var http = false;

    if(navigator.appName == "Microsoft Internet Explorer") {
      http = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
       http = new XMLHttpRequest();
    }

    function replace() {
      http.open("GET", "tester.txt", true);
      http.onreadystatechange=function() {
        if(http.readyState == 4) {
          document.getElementById('foo').innerHTML = http.responseText;
        }
      }
      http.send(null);
    }
  </script> 
</head> 
<body> 

<p><a href="javascript:replace()">Replace Text</a></p> 

<div id="foo" style="background: #CFEBFF; border: 2px solid #0090F4; padding: 4px"> 
  Hello, world!
</div> 

</body> 
</html> 

When ever I click the link i gave up there. It just shows a blank. Yet my text file in the same directory (called te开发者_运维技巧ster.txt) holds some information. Help please? Thank you.


Unless you're really committed to learning how to do this the hard way, I would really recommend jQuery for this. It handles all that weird browser difference for you with a great library for AJAX requests. To make the call you want, it would be as simple as:

$.get('tester.txt').success(function (receivedData) {
  //do something with receivedData
});

If you are looking to do this the hard way, well, best of luck to you. You could look at how jQuery implements it for some clues, lines 7442 to 7980.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜